Back to Snippets
ReactTypeScript

React Toggle Component

An accessible toggle switch component with smooth animation.

reactcomponenttoggleswitch
import { useState } from class=class="text-emerald-400">"text-emerald-400">'react'

interface ToggleProps {
  defaultChecked?: boolean
  onChange?: (checked: boolean) => void
  label?: string
}

export function Toggle({ defaultChecked = false, onChange, label }: ToggleProps) {
  const [checked, setChecked] = useState(defaultChecked)

  const handleToggle = () => {
    const next = !checked
    setChecked(next)
    onChange?.(next)
  }

  return (
    <label className=class="text-emerald-400">"inline-flex items-center gap-3 cursor-pointer">
      <button
        role=class="text-emerald-400">"switch"
        aria-checked={checked}
        onClick={handleToggle}
        className={class="text-emerald-400">`relative w-11 h-6 rounded-full transition-colors duration-200 ${
          checked ? class=class="text-emerald-400">"text-emerald-400">'bg-blue-600' : class=class="text-emerald-400">"text-emerald-400">'bg-gray-300'
        }`}
      >
        <span className={class="text-emerald-400">`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform duration-200 ${
          checked ? class=class="text-emerald-400">"text-emerald-400">'translate-x-5' : class=class="text-emerald-400">"text-emerald-400">'translate-x-0'
        }`} />
      </button>
      {label && <span className=class="text-emerald-400">"text-sm font-medium">{label}</span>}
    </label>
  )
}

How to Use

Use as a controlled or uncontrolled toggle: <Toggle label="Notifications" onChange={(v) => console.log(v)} />. It uses role='switch' for accessibility and smooth CSS transitions.

Related Technology

React

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call