Design an Animated Toggle Switch Button using framer-motion & React
In this article, we are going to learn how to create an animated toggle switch button using
- NodeJS should be installed
- Knowledge of HTML/CSS.
- Basic knowledge of ReactJS.
Creating React Application And Installing Module :
Step 1: Now, you will start a new project using create-react-app so open your terminal and type:
npx create-react-app toggle-switch
Step 2: After creating your project folder i.e. toggle-switch, move to it using the following command.
Step 3: Add the npm packages you will need during the project :
npm install framer-motion
npm i framer-motion
Step 4: Now open your newly created project with your favorite code editor, I am using Visual Studio Code and will recommend you to use the same.
Open the src folder and delete the following files :
- App.test.js (if any)
Project structure: Your folder structure tree should look like this.
I will highly recommend you to write this code instead of just copy-pasting & play with the CSS, tweak it a little according to your taste and need.
- We are going to make use const & arrow function to code a utility component “Switch” which will be used to create toggle switch.
- In Switch, we will write code to change the class name and image source according to the state of isOn passed as a prop by destructuring.
- Toggle switch and its animation will be achieved using framer-motion’s motion.div component and animate attribute for it.
- In the App, we are going to use useState hook to manage the state of “isOn” that is changed by clicking on the toggle switch button which in turn is used to change the class name, background-color and image source.
- React useEffect hook is used to create a side effect whenever the state of “isOn” is changed to make changes in the background color of the entire page accordingly.
Step to Run Application: Run the application using the following command from the root directory of the project.
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Please Login to comment...