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'}
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.
Top comments (0)