Stylish and Reusable Toggle Switch Component with React and Tailwind CSS
Toggle switches are an essential part of many modern web applications. They let users turn options ON or OFF with a single click, improve the UX (user experience). In this article, you will get the code for sleek, and reusable toggle switch component in React with Tailwind CSS, with necessary explanation.
This component is fully customizable and easy to integrate into any project. Let’s dive in!
Tailwind Toggle Switch Component Preview
Here’s how the toggle switch looks and functions:
- OFF State: 🌙
- ON State: 🔆
Tailwind Toggle Switch Component Code
Below is the code for the reusable toggle switch. You can copy and paste it directly into your React project.
1import { ChangeEvent, FC } from 'react' 2 3interface ToggleSwitchProps { 4 switchState: boolean 5 handleSwitchState: (e: ChangeEvent<HTMLInputElement>) => void 6} 7const ToggleSwitch: FC<ToggleSwitchProps> = ({ 8 switchState, 9 handleSwitchState, 10}) => { 11 return ( 12 <label 13 className="relative inline-block h-[22px] w-11 cursor-pointer" 14 aria-label="Toggle Switch" 15 > 16 <div className="absolute right-0 top-0 flex h-full w-full rounded-3xl border border-[#E5E5E5] bg-white transition-all duration-300 ease-out has-[:checked]:bg-[#a00c92]"> 17 <input 18 type="checkbox" 19 className="peer h-0 w-0 opacity-0" 20 checked={switchState} 21 onChange={handleSwitchState} 22 /> 23 <span className="absolute left-[2px] top-[2px] min-h-4 min-w-4 rounded-full bg-[#C8C8C8] transition-all duration-300 ease-out peer-checked:translate-x-[22px] peer-checked:bg-white"></span> 24 </div> 25 </label> 26 ) 27} 28 29export default ToggleSwitch
How to Use the Component
- Import the Component: Add the
ToggleSwitch
component to your desired file. - Manage State in Parent Component: Use React’s
useState
to manage the toggle switch state.
1import { ChangeEvent, useState } from 'react' 2import ToggleSwitch from './components/SwitchButton' 3 4const App = () => { 5 const [isSwitchOn, setIsSwitchOn] = useState(false) 6 7 const handleSwitchState = (e: ChangeEvent<HTMLInputElement>) => { 8 const newState = e.target.checked 9 setIsSwitchOn(newState) 10 } 11 console.log('Switch state:', isSwitchOn) 12 13 return ( 14 <div className="flex min-h-screen flex-col items-center justify-center bg-gray-100"> 15 <h1 className="mb-4 text-2xl font-bold">Reusable Toggle Switch Demo</h1> 16 <ToggleSwitch 17 switchState={isSwitchOn} 18 handleSwitchState={handleSwitchState} 19 /> 20 <p className="mt-4 text-lg"> 21 Switch is currently: {isSwitchOn ? 'ON 🔆' : 'OFF 🌙'} 22 </p> 23 </div> 24 ) 25} 26 27export default App
Do you have any custom component request? feel free to contact me on LinkedIn.