Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Sun Apr 16 2023

How to switch between icons with animation in React

In this guide, we will show how to switch between two icons with a fade in animation in React. We got the idea to write this tutorial after we implemented a little animation on our night-mode switch in the header.

Example of how it looks

gif

Our component

Let's start with our React component. In order to get the animation, we need to have the elements in the DOM tree to begin with, hence we will switch the display property in order to get our animation effect to work.

Let's create our state first. On top of your component, initialize your state as follows.

const [isNightMode, setNightMode] = useState(false);

And render the icons like this.

<div className={style.modeSwitch} onClick={() => setNightMode(!isNightMode)}> <img style={{ display: isNightMode ? "block" : "none" }} className={style.themeButton} src={"/icons/lightmode.svg"} alt="mode-switch" /> <img style={{ display: !isNightMode ? "block" : "none" }} className={style.themeButton} src={"/icons/darkmode.svg"} alt="mode-switch" /> </div>

Get the icons here.

All right, so we have our div container that will wrap the icons. When we click on the icon container, we will change the state value and also the icon. We are using the isNightMode to alter the display property value between block and none.

Let's do some styling.

.modeSwitch { display: flex; cursor: pointer; .themeButton { width: 30px; height: 30px; animation: fadeInAnimation ease 1.5s; animation-iteration-count: 1; animation-fill-mode: forwards; } } @keyframes fadeInAnimation { 0% { opacity: 0; } 100% { opacity: 1; } }

We are setting our animation to last for 1.5 seconds, you can change the value so it suits your preferences.

Outro

That's it. Now we have created a little animation on our icons so it feels a little bit smoother to interact with it. The tricky part is that the elements should be in the DOM tree before applying the animation to it, so we cannot do like:

<div>{isNightMode ? <img src="lightIcon" /> : <img src="darkIcon" />}</div>

then our animation will not do anything.

I hope this short tutorial gave you some help, and thanks for reading!

signatureSun Apr 16 2023
See all our articles