Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
Like Article
  • Last Updated : 12 Mar, 2021
Improve Article
Save Article
Like Article

In this article, we are going to learn how to create an animated toggle switch button using

  • framer-motion
  • React.js

Prerequisites:

  1. NodeJS should be installed
  2. Knowledge of JavaScript (ES6).
    1. Arrow function (ES6)
    2. Ternary operator
    3. document.body.style.backgroundColor
  3. Knowledge of HTML/CSS.
  4. Basic knowledge of ReactJS.
    1. React useState
    2. 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 :

  1. logo.svg
  2. serviceWorker.js
  3. setupTests.js
  4. index.css
  5. 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.


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!