Stackbits
Buttons > Toggle Button

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

1
npm i framer-motion

Component

Create a file toggle-button.tsx in your components folder and paste this code

1
'use client';
2
3
import { motion } from 'framer-motion';
4
import React, { useState } from 'react';
5
6
type ToggleButtonProps = {
7
options: Array<{
8
icon: React.ReactNode;
9
value: string;
10
}>;
11
defaultValue?: string;
12
onChange?: (value: string) => void;
13
};
14
15
const ToggleButton = ({ options, defaultValue, onChange, ...props }: ToggleButtonProps) => {
16
const [currentIndex, setCurrentIndex] = useState(
17
options.findIndex((option) => option.value === defaultValue) || 0
18
);
19
20
const onClick = () => {
21
const nextIndex = (currentIndex + 1) % options.length;
22
setCurrentIndex(nextIndex);
23
if (onChange) onChange(options[nextIndex].value);
24
};
25
26
return (
27
<motion.div
28
className="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}
30
onClick={onClick}
31
whileTap={{ scale: 0.9 }}
32
transition={{ duration: 0.1, ease: 'backOut' }}
33
role="button"
34
tabIndex={0}
35
onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && onClick()}
36
aria-label="Toggle button"
37
>
38
<motion.div
39
animate={{ y: -currentIndex * 64 }}
40
transition={{ type: 'spring', stiffness: 300, damping: 20 }}
41
className="flex flex-col pb-1"
42
style={{ 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
};
53
54
export default ToggleButton;

Usage

1
<ToggleButton
2
// onChange={(value) => console.log(value)}
3
options={[
4
{
5
icon: <Sun />,
6
value: 'Sun'
7
},
8
{
9
icon: <Moon />,
10
value: 'Moon'
11
},
12
{
13
icon: <Rocket />,
14
value: 'Rocket'
15
}
16
]}
17
defaultValue="Sun"
18
/>

⭐️ Got a question or feedback?
Feel free to reach out!