Sitemap
Matthew Wall

Matthew Wall

An aspiring homesteader and avid believer that Web3 has the potential to change the world.

Framer Motion Switch Component

5 min readJan 14, 2023

--

toggle switch animated using framer-motion

Framer Motion is a popular animation library for React that allows for the creation of complex animations with minimal code and high abstraction. In this blog post, we will take a look at how to implement this library to create a pretty fun switch component which changes background color and position simultaneously.

First, you will need to install the Framer Motion library by running the following command in your terminal:

npm install framer-motion
// or
yarn add framer-motion

Once you have the library installed, you can import the motion component and the useAnimation hook from the library in your React component:

import { motion } from "framer-motion"

Let’s start by setting up some initial components we’ll need. If you take a look at any switch (or toggle) component, you’ll notice that there are two main components.

  1. The background
  2. The circle/thumb that is controlled and moves from off to on state

Let’s dive right in and focus on setting up the two components. I’m going to utilize styled-components as my styling library because that’s what I like, but you can use vanilla CSS or your choice of library.

Toggle Component

const Toggle = styled(motion.div)`
width: 48px;
height: 24px;
border-radius: 16px;
position: relative;
cursor: pointer;
`;

Let’s take a look at what we have here. We’ve setup a <Toggle/> component that will be responsible for acting as the background for our switch component. It’s important to do some very basic math here. Whatever width size you choose (in this case, 48px), your height has to be exactly half of that (respectively, 24px). And that’s really all you have to worry about when it comes to the background (for now…).

Circle Component

The only other component, and arguably the one that requires a bit more babysitting, is the circle component.

const Circle = styled(motion.div)`
width: 18px;
height: 18px;
border-radius: 50%;
position: absolute;
cursor: pointer;
top: 3px;
`;

Here we define the width and height of the circle to be the same size in pixels. You can adjust this a bit if you wish, but keep in mind the math here has to be: height — (padding*2) . So for example, if you wanted to make the height of your switch 48px , and a padding of 8px around the circle, your component would look like this. 48-(8*2) = 32px.

const Circle = styled(motion.div)`
width: 32px;
height: 32px;
border-radius: 50%;
position: absolute;
cursor: pointer;
top: 4px;
`;

Another thing to note is that the top position has to be exactly half of your padding (in this case, 4px). This logic would also adjust your background width to be 96px . However, for the rest of this post, we’ll use the original sizing. Let’s continue…

The Animations

Okay great. So we’ve done some basic styling. Big whoop, right? Alright I hear you. Let’s dive in to the fun stuff.

Get Matthew Wall’s stories in your inbox

Join Medium for free to get updates from this writer.

We’re going to setup two sets of variants, one for the circle, and one for the background. If you don’t know what variants are, basically it’s just a set of objects that define the object in that state. Framer motion uses these to animate between variants and allows us to abstract animations extremely easily this way.

The Circle

const circle = {
off: {
x: "4px",
backgroundColor: "rgb(247, 242, 242)"
},
on: {
x: "26px",
backgroundColor: "#786EF2"
}
};

Here we have two states, on and off . We’ll see this is responsible for moving the circle from x position 4px to 26px . To calculate these positions, we can simple take into account the full width of the switch, minus the padding we want left on the sides, and minus the width of the circle. That number will give us the amount of movement we have on the x plane to work with. 48-(4*2)-18 = 22px . You can see we don’t want to start at x=0, since that would be at the complete left-hand side of the background, so we start at x=4. This means our ending position is x=4+22 => 26px. Simple! This is optional, but if we want to change the color of the circle from on to off , we simply define that in these variants too.

The Toggle

const toggle = {
off: {
backgroundColor: "#616161"
},
on: {
backgroundColor: "rgba(120, 110, 242, 0.2)"
}
};

I’ll keep this one brief since it looks pretty similar to the circle. Here we’re just toggling between background colors. Super simple! You can add more flare here if you wish, but this does the trick, and it looks great to me.

Wrapping Up

Let’s throw this all together into a component we can use. Lucky for us, framer motion provides a wonderful utility function useCycle that we can use for the state management here. However, if you were to persist the choice of the toggle, you should inject an initial state into this component.

import styled from "styled-components";
import { motion } from "framer-motion";

const circle = {
off: {
x: "4px",
backgroundColor: "rgb(247, 242, 242)"
},
on: {
x: "26px",
backgroundColor: "#786EF2"
}
};

const toggle = {
off: {
backgroundColor: "#616161"
},
on: {
backgroundColor: "rgba(120, 110, 242, 0.2)"
}
};

const Toggle = styled(motion.div)`
width: 48px;
height: 24px;
border-radius: 16px;
position: relative;
cursor: pointer;
`;

const Circle = styled(motion.div)`
width: 18px;
height: 18px;
border-radius: 50%;
position: absolute;
cursor: pointer;
top: 3px;
`;

interface ToggleProps {
on: number;
check: React.Dispatch<React.SetStateAction<boolean>>;
}

const ToggleComponent = ({ on, check }: ToggleProps) => {
return (
<Toggle
onClick={() => check((prev) => !prev)}
variants={toggle}
initial={on ? "on" : "off"}
animate={on ? "on" : "off"}
transition={{
backgroundColor: {
duration: 0.01
}
}}
>
<Circle
variants={circle}
initial={on ? "on" : "off"}
animate={on ? "on" : "off"}
transition={{
backgroundColor: {
duration: 0.01
},
x: { type: "spring", stiffness: 200, damping: 17.5 }
}}
/>
</Toggle>
);
};

export default ToggleComponent;

And voila! Your very own switch component with very basic styling and a super simple but effective animation. Did I mention you can run Minecraft at 60fps while toggling it? Unbelievable. I know.

Here’s a code sandbox to play around with this if you want to: https://codesandbox.io/s/mtw-switch-3f8d6q

Thanks for reading. I hope this helped. Happy animating!

--

--

Written by Matthew Wall

An aspiring homesteader and avid believer that Web3 has the potential to change the world.