Switch Button Magic By Framer Motion

manoryanir

yanir manor

Posted on January 12, 2022

Switch Button Magic By Framer Motion

Image description

How to create an animated switch button in React?
First, we install tailwindcss for this job
There will be two elements in the switch button: a container and a bull.

container
cursor-pointer w-16 h-10 flex items-center bg-gray-300 rounded-full p-1
bull
bg-white w-8 h-8 rounded-full shadow-md

It's that easy to have a static switch button.
now we need to add click behavior.
lets create a simple use state hook to toggle active state.
const [isSelected, setSelected] = useState(false)
on container we will add click handler
onClick={() => setSelected(!isSelected)}
and interactive css

${isSelected ? 'bg-red-500 justify-end' : 'justify-start'}
Enter fullscreen mode Exit fullscreen mode

Take it for a test.
its working but something is missing.
Yes, animation, are you ready for the magic 🪄?
Change the bull div to be motion div.
Add the magic layout property.
ta dam 🎉🎉🎉 you have a nice switch button.

you can see and play with the code - run in terminal - npm run build && npm run preview.

💖 💪 🙅 🚩
manoryanir
yanir manor

Posted on January 12, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related