Docs
Toggle Switch
A toggle switch that can be used to turn on or off a feature.
requires interactiontoggle
Installation
Update tailwind.config.js
theme: {
extend: {
colors: {
foreground: "hsl(var(--foreground))",
}
},
},
Run the following command
It will create a new file called toggle-switch.tsx
inside the components/animata/button
directory.
mkdir -p components/animata/button && touch components/animata/button/toggle-switch.tsx
Paste the code
Open the newly created file and paste the following code:
"use client";
import { useState } from "react";
interface IToggleSwitchProps {
onChange?: (value: boolean) => void;
defaultChecked?: boolean;
}
const ToggleSwitch = ({ onChange, defaultChecked }: IToggleSwitchProps) => {
const [isChecked, setIsChecked] = useState<boolean>(defaultChecked ?? false);
const handleCheckboxChange = () => {
const newCheckedState = !isChecked;
setIsChecked(newCheckedState);
onChange?.(newCheckedState);
};
return (
<>
<label className="flex cursor-pointer select-none items-center">
<div className="relative">
<input
type="checkbox"
checked={isChecked}
onChange={handleCheckboxChange}
className="sr-only"
/>
<div
className={`box block h-8 w-14 rounded-full ${isChecked ? "bg-muted" : "bg-muted"}`}
/>
<div
className={`absolute left-1 top-1 flex h-6 w-6 items-center justify-center rounded-full transition ${
isChecked ? "translate-x-full bg-foreground/75" : "bg-foreground/50"
}`}
/>
</div>
</label>
</>
);
};
export default ToggleSwitch;
Credits
Built by Aadarsh Baral