In this tutorial, we’ll create a toggle switch in React.js using Tailwind CSS. We’ll explore examples of a simple toggle switch in React and using the Headless UI library, all styled with Tailwind CSS.
Tool Use
React JS
Tailwind CSS
Headless UI
First you need to setup react project with tailwind css. You can install manually or you read below blog.
How to install Tailwind CSS in React
Install & Setup Vite + React + Typescript + Tailwind CSS 3
Example 1
Build a toggle switch input with react hooks and tailwind css.
import { useState } from "react";
export default function Toggle() {
const [enabled, setEnabled] = useState(false);
return (
<div className="relative flex flex-col items-center justify-center min-h-screen overflow-hidden">
<div className="flex">
<label class="inline-flex relative items-center mr-5 cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={enabled}
readOnly
/>
<div
onClick={() => {
setEnabled(!enabled);
}}
className="w-11 h-6 bg-gray-200 rounded-full peer peer-focus:ring-green-300 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"
></div>
<span className="ml-2 text-sm font-medium text-gray-900">
ON
</span>
</label>
</div>
</div>
);
}
Example 2
Create a toggle switch input with react and tailwind css and Headless ui.
To get started, install Headless UI via npm:
npm install @headlessui/react
import { useState } from 'react'
import { Switch } from '@headlessui/react'
export default function Toggle() {
const [enabled, setEnabled] = useState(false)
return (
<div className="grid h-screen place-items-center">
<Switch
checked={enabled}
onChange={setEnabled}
className={`${enabled ? 'bg-teal-900' : 'bg-teal-700'}
relative inline-flex h-[38px] w-[74px] shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-opacity-75`}
>
<span className="sr-only">Use setting</span>
<span
aria-hidden="true"
className={`${enabled ? 'translate-x-9' : 'translate-x-0'}
pointer-events-none inline-block h-[34px] w-[34px] transform rounded-full bg-white shadow-lg ring-0 transition duration-200 ease-in-out`}
/>
</Switch>
</div>
)
}