Toggle Button
A Toggle Button is a sleek, interactive UI component that lets users seamlessly switch between multiple states—like light/dark mode, on/off, or enabled/disabled—with a single click. Perfect for modern web apps, it enhances usability, efficiency, and user experience, making interactions feel smooth and intuitive. Whether you're toggling themes, preferences, or features, this dynamic button keeps your interface clean, functional, and engaging! 🚀
Preview
Follow below steps 👇🏻
Install dependencies
1npm i framer-motion
Component
Create a file toggle-button.tsx in your components folder and paste this code
1'use client';23import { motion } from 'framer-motion';4import React, { useState } from 'react';56type ToggleButtonProps = {7options: Array<{8icon: React.ReactNode;9value: string;10}>;11defaultValue?: string;12onChange?: (value: string) => void;13};1415const ToggleButton = ({ options, defaultValue, onChange, ...props }: ToggleButtonProps) => {16const [currentIndex, setCurrentIndex] = useState(17options.findIndex((option) => option.value === defaultValue) || 018);1920const onClick = () => {21const nextIndex = (currentIndex + 1) % options.length;22setCurrentIndex(nextIndex);23if (onChange) onChange(options[nextIndex].value);24};2526return (27<motion.div28className="relative h-[64px] w-[64px] overflow-hidden rounded-full border-2 border-neutral-600 hover:border-neutral-200 transition-all hover:bg-white/10 focus:outline-none focus:ring-2 focus:ring-white/30"29{...props}30onClick={onClick}31whileTap={{ scale: 0.9 }}32transition={{ duration: 0.1, ease: 'backOut' }}33role="button"34tabIndex={0}35onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && onClick()}36aria-label="Toggle button"37>38<motion.div39animate={{ y: -currentIndex * 64 }}40transition={{ type: 'spring', stiffness: 300, damping: 20 }}41className="flex flex-col pb-1"42style={{ height: `${options.length * 64}px` }}43>44{options.map((option) => (45<div key={option.value} className="h-[64px] w-full flex items-center justify-center">46{option.icon}47</div>48))}49</motion.div>50</motion.div>51);52};5354export default ToggleButton;
Usage
1<ToggleButton2// onChange={(value) => console.log(value)}3options={[4{5icon: <Sun />,6value: 'Sun'7},8{9icon: <Moon />,10value: 'Moon'11},12{13icon: <Rocket />,14value: 'Rocket'15}16]}17defaultValue="Sun"18/>
⭐️ Got a question or feedback?
Feel free to reach out!