Design an Animated Toggle Switch Button using framer-motion & React - GeeksforGeeks

12 Mar, 2021
In this article, we are going to learn how to create an animated toggle switch button using
framer-motion
React.js
Prerequisites:
NodeJS should be installedKnowledge of JavaScript (ES6).Arrow function (ES6)Ternary operatordocument.body.style.backgroundColorKnowledge of HTML/CSS.Basic knowledge of ReactJS.React useStateReact useEffect
NodeJS should be installed
Knowledge of JavaScript (ES6).Arrow function (ES6)Ternary operatordocument.body.style.backgroundColor
Arrow function (ES6)Ternary operatordocument.body.style.backgroundColor
Arrow function (ES6)
Ternary operator
document.body.style.backgroundColor
Knowledge of HTML/CSS.
Basic knowledge of ReactJS.React useStateReact useEffect
React useStateReact useEffect
React useState
React useEffect
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.
cd toggle-switch
Step 3: Add the npm packages you will need during the project :
npm install framer-motion
or
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 :
logo.svgserviceWorker.jssetupTests.jsindex.cssApp.test.js (if any)
logo.svg
serviceWorker.js
setupTests.js
index.css
App.test.js (if any)
Project structure: Your folder structure tree should look like this.
Folder structure
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.
Approach:
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.
Example:
App.js
import React from "react";import { useState, useEffect } from "react";import { motion } from "framer-motion";import "./App.css";  const Switch = ({ isOn, ...rest }) => {    // initialize the customClassName according to the  // state of the "isOn" using ternary operator  const customClassName =      `toggleSwitch ${isOn ? "on" : "off"}`;    // initialize the src according to the  // state of the "isOn" using ternary operator  const src = isOn    ? "Toggle 1st Image link"    : "Toggle 2nd Image link";    return (    <motion.div animate className=        {customClassName} {...rest}>      <motion.div animate>        <img src={src} />      </motion.div>    </motion.div>  );};  const App = () => {  // useState hook is used to manage the state of  // "isOn" that is used to change the className,   // background-color and img src accordingly  const [isOn, setIsOn] = useState(false);    useEffect(() => {    // background-color changes every time "isOn"     // changes using JavaScript DOM methods    document.body.style.backgroundColor =               isOn ? "#1c1c1c" : "#ffffff";  }, [isOn]);    return <Switch isOn={isOn} onClick={() =>                           setIsOn(!isOn)} />;};  export default App;
App.css
body {  margin: 0;  display: flex;  justify-content: center;  align-items: center;  min-height: 100vh;  /* for smooth transition*/  transition: 0.5s ease-in-out;}  * {  box-sizing: border-box;}  .toggleSwitch {  width: 170px;  height: 100px;  border-radius: 100px;  padding: 10px;  display: flex;  cursor: pointer;  z-index: 2;}  /* CSS for switch when "on"*/.toggleSwitch.on {  background-color: #1aad66;  justify-content: flex-end;  /* for smooth transition*/  transition: 0.5s ease-in-out;}  /*CSS for switch when "off"*/.toggleSwitch.off {  background-color: #dddddd;  justify-content: flex-start;}  .toggleSwitch div {  width: 80px;  height: 80px;  border-radius: 100%;}  img {  width: 80px;  height: 80px;  border-radius: 100%;}
index.js
import React from "react";import ReactDOM from "react-dom";import App from "./App";  const rootElement = document.getElementById("root");ReactDOM.render(  <React.StrictMode>    <App />  </React.StrictMode>,  rootElement);
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Framer-motion
React-Questions
Technical Scripter 2020
ReactJS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript