Create a dynamic load side page with animation in React.js

Mukesh Prajapati
2 min readMay 13, 2023

--

When we want to render HTML on condition we have one challenge we can’t add animation to the HTML code block.

Today we are going to solve this problem with some easy steps.

Let’s understand with one example you can implement it into your existing or new project.

So firstly we need one hook useDidMountEffect React doesn’t provide this hook to us in their default hooks that’s why we will create this hook itself.
But before creating it, understand why we need this hook and what is the use of this hook.

useDidMountEffect As its use is already cleared by its name didMountEffect this hook will be run when its dependencies are changed. And also it will not run on component load.

Let’s create and export hook in utils/hooks.js or any other file where you created your all custom hooks.

export const useDidMountEffect = (func = () => {}, deps) => {
const didMount = useRef(false);

useEffect(() => {
if (didMount.current) func();
else didMount.current = true;
}, deps);
};

Now create the main file where you want to load your side page.

const App = () => {
return(
<div className="box">
<h1>Click on the button and open sidepage</h1>
<button
onClick={() => {
setOpen(true)
}}
className="button">
Special Button
</button>
</div>
);
}

Create a side page file.

const SidePage =({open= false, setOpen =()=>{}})=>{
const [isVisible,setVisible] =useState(false);

useDidMountEffect(()=>{
setTimer({ isOpen: open, isVisible, setVisible });
},[open]);

return (
isVisible?
<div className={`side-page ${open ?'open':'closed'}`}
style={{
transition: "0.5s",
animation: `${open ? "openSideModal" : "closeSideModal"} .5s 1`
}}
>
<div onClick={()=>setOpen(false)}>X</div>
<h1>This is Side Page</h1>
</div>: null
)
}

We used useDidMountEffect hook and also created isVisible state when isVisible is true our side page is available in Dom else the side-page is not showing on Dom. In this file, we use one more function setTimer, this function basically use to remove side-page from the dom this function is setVisible false after the delay time.

setTimerFunction

let timer = null;
function setTimer({ isOpen, isVisible, setVisible = () => {}, delay = 400 }) {
if (isOpen) {
setVisible(isOpen);
} else {
// clear any existing timer
if (timer != null) {
clearTimeout(timer);
}

// hide after `delay` milliseconds
timer = setTimeout(() => {
setVisible(!isVisible);
timer = null;
}, delay);
}
}

Let’s call side-page component on our main page.

const App = () => {
const [open, setOpen] = useState(false);
return(
<>
<SidePage open={open} setOpen={setOpen}/>
<div className="box">
<h1>Click on the button and open sidepage</h1>
<button
onClick={() => {
setOpen(true)
}}
className="button">
Open side page
</button>
</div>
</>
);
}

Great: your side page is ready with dynamic load with animation.

Find the full code here:

Follow and subscribe for more Thank you for reading 😊

--

--