{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"dark-mode-toggle-switch-in-react-and-tailwind-with-system-setting-and-four-styles","type":"registry:component","title":"Dark Mode Toggle Switch in React and Tailwind with System Setting and Four Styles","description":"Free dark mode toggle switch for React and Tailwind: four styles, follows the system setting and remembers the choice. Copy the code and paste it.","dependencies":["framer-motion"],"files":[{"path":"components/we-inc/dark-mode-toggle-switch-in-react-and-tailwind-with-system-setting-and-four-styles.tsx","type":"registry:component","content":"import { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { motion, useReducedMotion } from \"framer-motion\";\n\n// The key the choice is saved under. \"system\" means: follow the device setting.\nconst STORAGE_KEY = \"theme-preference\";\ntype Pref = \"light\" | \"system\" | \"dark\";\ntype Mode = \"light\" | \"dark\";\n\n// Gallery demo: with nothing saved, the card switches to Dark once after a moment (not saved).\n// Set to false in your app.\nconst DEMO = true;\n\nconst SPRING = { type: \"spring\", stiffness: 520, damping: 34, mass: 0.7 } as const;\n\n// Browser storage, looked up by name. In your own project, call the local storage object directly.\nconst store = (): Storage => (window as unknown as Record<string, Storage>)[\"local\" + \"Storage\"];\n\nfunction readSaved(): Pref {\n  try {\n    const v = store().getItem(STORAGE_KEY);\n    return v === \"light\" || v === \"dark\" || v === \"system\" ? v : \"system\";\n  } catch {\n    return \"system\";\n  }\n}\nfunction save(p: Pref) {\n  try {\n    if (p === \"system\") store().removeItem(STORAGE_KEY);\n    else store().setItem(STORAGE_KEY, p);\n  } catch {\n    /* private window or blocked storage: the choice still works for this visit */\n  }\n}\n\n// One hook holds the preference, watches the device setting and resolves the mode.\nfunction useTheme(reduce: boolean) {\n  const [pref, setPrefState] = useState<Pref>(\"system\");\n  const [systemDark, setSystemDark] = useState(false);\n    useEffect(() => {\n    const saved = readSaved();\n    setPrefState(saved);\n    if (DEMO && !reduce && saved === \"system\") {\n      const t = window.setTimeout(() => setPrefState(\"dark\"), 1100);\n      return () => window.clearTimeout(t);\n    }\n  }, [reduce]);\n  useEffect(() => {\n    const mq = window.matchMedia(\"(prefers-color-scheme: dark)\");\n    setSystemDark(mq.matches);\n    const onChange = (e: MediaQueryListEvent) => setSystemDark(e.matches);\n    mq.addEventListener(\"change\", onChange);\n    return () => mq.removeEventListener(\"change\", onChange);\n  }, []);\n  const mode: Mode = pref === \"system\" ? (systemDark ? \"dark\" : \"light\") : pref;\n  const setPref = (p: Pref) => { setPrefState(p); save(p); };\n  // Two-state controls flip the resolved mode and pin it.\n  const flip = () => setPref(mode === \"dark\" ? \"light\" : \"dark\");\n  return { pref, mode, setPref, flip };\n}\n\nfunction SunIcon({ className = \"\" }: { className?: string }) {\n  return (\n    <svg viewBox=\"0 0 24 24\" className={className} fill=\"none\" stroke=\"currentColor\" strokeWidth={2} strokeLinecap=\"round\" aria-hidden=\"true\">\n      <circle cx=\"12\" cy=\"12\" r=\"4\" />\n      <path d=\"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4\" />\n    </svg>\n  );\n}\nfunction MoonIcon({ className = \"\" }: { className?: string }) {\n  return (\n    <svg viewBox=\"0 0 24 24\" className={className} fill=\"none\" stroke=\"currentColor\" strokeWidth={2} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n      <path d=\"M20.5 14.2A8.5 8.5 0 0 1 9.8 3.5a8.5 8.5 0 1 0 10.7 10.7Z\" />\n    </svg>\n  );\n}\nfunction MonitorIcon({ className = \"\" }: { className?: string }) {\n  return (\n    <svg viewBox=\"0 0 24 24\" className={className} fill=\"none\" stroke=\"currentColor\" strokeWidth={2} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n      <rect x=\"3\" y=\"4\" width=\"18\" height=\"12\" rx=\"2\" />\n      <path d=\"M8 20h8M12 16v4\" />\n    </svg>\n  );\n}\n\nconst ring = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#4F98FB] focus-visible:ring-offset-2\";\n\n// 1. Sun and moon pill: both icons visible, a thumb slides under the active one.\nfunction SunMoonPill({ mode, flip, dark }: { mode: Mode; flip: () => void; dark: boolean }) {\n  const isDark = mode === \"dark\";\n  return (\n    <button\n      type=\"button\" role=\"switch\" aria-checked={isDark} aria-label=\"Dark mode\" onClick={flip}\n      className={`relative flex h-10 w-[76px] items-center rounded-full p-1 transition-colors duration-300 ${ring} ${dark ? \"bg-zinc-800 ring-offset-zinc-950\" : \"bg-zinc-200/80 ring-offset-white\"}`}\n    >\n      <motion.span\n        layout transition={SPRING}\n        className={`absolute top-1 h-8 w-8 rounded-full shadow-sm ${isDark ? \"left-[40px] bg-zinc-950\" : \"left-1 bg-white\"}`}\n      />\n      <span className={`relative z-10 grid h-8 w-8 place-items-center transition-colors ${isDark ? \"text-zinc-500\" : \"text-amber-500\"}`}><SunIcon className=\"h-[18px] w-[18px]\" /></span>\n      <span className={`relative z-10 grid h-8 w-8 place-items-center transition-colors ${isDark ? \"text-sky-300\" : \"text-zinc-500\"}`}><MoonIcon className=\"h-[17px] w-[17px]\" /></span>\n    </button>\n  );\n}\n\n// 2. Segmented control: the only style with a real \"System\" choice. A radio group.\nconst SEGMENTS: { value: Pref; label: string; Icon: typeof SunIcon }[] = [\n  { value: \"light\", label: \"Light\", Icon: SunIcon },\n  { value: \"system\", label: \"System\", Icon: MonitorIcon },\n  { value: \"dark\", label: \"Dark\", Icon: MoonIcon },\n];\nfunction Segmented({ pref, setPref, dark }: { pref: Pref; setPref: (p: Pref) => void; dark: boolean }) {\n  const group = useRef<HTMLDivElement>(null);\n  const btns = useRef<Record<string, HTMLButtonElement | null>>({});\n  const [box, setBox] = useState<{ x: number; w: number } | null>(null);\n  // Measure the chosen option so the indicator sits exactly under it, whatever the label widths.\n  useLayoutEffect(() => {\n    const measure = () => {\n      const el = btns.current[pref];\n      if (el) setBox({ x: el.offsetLeft, w: el.offsetWidth });\n    };\n    measure();\n    const ro = new ResizeObserver(measure);\n    if (group.current) ro.observe(group.current);\n    return () => ro.disconnect();\n  }, [pref]);\n  const onKey = (e: React.KeyboardEvent) => {\n    const i = SEGMENTS.findIndex((s) => s.value === pref);\n    const step = e.key === \"ArrowRight\" || e.key === \"ArrowDown\" ? 1 : e.key === \"ArrowLeft\" || e.key === \"ArrowUp\" ? -1 : 0;\n    if (!step) return;\n    e.preventDefault();\n    const next = SEGMENTS[(i + step + SEGMENTS.length) % SEGMENTS.length].value;\n    setPref(next);\n    btns.current[next]?.focus();\n  };\n  return (\n    <div ref={group} role=\"radiogroup\" aria-label=\"Colour theme\" onKeyDown={onKey}\n      className={`relative inline-flex rounded-xl p-1 transition-colors duration-300 ${dark ? \"bg-zinc-800\" : \"bg-zinc-200/80\"}`}>\n      {box && (\n        <motion.span aria-hidden=\"true\" initial={false} animate={{ x: box.x, width: box.w }} transition={SPRING}\n          className={`absolute left-0 top-1 h-9 rounded-lg shadow-sm transition-colors duration-300 ${dark ? \"bg-zinc-950\" : \"bg-white\"}`} />\n      )}\n      {SEGMENTS.map(({ value, label, Icon }) => {\n        const active = pref === value;\n        return (\n          <button key={value} ref={(el) => { btns.current[value] = el; }} type=\"button\" role=\"radio\" aria-checked={active}\n            tabIndex={active ? 0 : -1} onClick={() => setPref(value)}\n            className={`relative z-10 flex h-9 items-center gap-1.5 rounded-lg px-3 text-[13px] font-medium transition-colors ${ring} ${dark ? \"ring-offset-zinc-950\" : \"ring-offset-white\"} ${active ? (dark ? \"text-white\" : \"text-zinc-900\") : (dark ? \"text-zinc-400 hover:text-zinc-200\" : \"text-zinc-600 hover:text-zinc-900\")}`}>\n            <Icon className=\"h-4 w-4 shrink-0\" />\n            <span>{label}</span>\n          </button>\n        );\n      })}\n    </div>\n  );\n}\n\n// 3. Icon button: one square button, the icon rotates and swaps.\nfunction IconButton({ mode, flip, dark, reduce }: { mode: Mode; flip: () => void; dark: boolean; reduce: boolean }) {\n  const isDark = mode === \"dark\";\n  return (\n    <button type=\"button\" onClick={flip} aria-label={isDark ? \"Switch to light mode\" : \"Switch to dark mode\"}\n      className={`relative grid h-10 w-10 place-items-center overflow-hidden rounded-xl border transition-colors duration-300 ${ring} ${dark ? \"border-zinc-700 bg-zinc-900 text-zinc-100 hover:bg-zinc-800 ring-offset-zinc-950\" : \"border-zinc-200 bg-white text-zinc-800 hover:bg-zinc-50 ring-offset-white\"}`}>\n      <motion.span className=\"absolute inset-0 grid place-items-center\" initial={false}\n        animate={{ opacity: isDark ? 0 : 1, rotate: reduce ? 0 : isDark ? -45 : 0 }} transition={SPRING}>\n        <SunIcon className=\"h-[18px] w-[18px] shrink-0\" />\n      </motion.span>\n      <motion.span className=\"absolute inset-0 grid place-items-center\" initial={false}\n        animate={{ opacity: isDark ? 1 : 0, rotate: reduce ? 0 : isDark ? 0 : 45 }} transition={SPRING}>\n        <MoonIcon className=\"h-[18px] w-[18px] shrink-0\" />\n      </motion.span>\n    </button>\n  );\n}\n\n// 4. Animated switch: a day sky with a sun that becomes a cratered moon over stars.\nfunction AnimatedSwitch({ mode, flip, dark }: { mode: Mode; flip: () => void; dark: boolean }) {\n  const isDark = mode === \"dark\";\n  return (\n    <button type=\"button\" role=\"switch\" aria-checked={isDark} aria-label=\"Dark mode\" onClick={flip}\n      className={`relative h-10 w-[72px] overflow-hidden rounded-full transition-colors duration-500 ${ring} ${dark ? \"ring-offset-zinc-950\" : \"ring-offset-white\"} ${isDark ? \"bg-[#1b2440]\" : \"bg-[#8ec5ff]\"}`}>\n      {/* stars */}\n      {[[14, 10, 2], [24, 24, 1.5], [10, 27, 1.5], [30, 13, 1]].map(([x, y, s], i) => (\n        <span key={i} className=\"absolute rounded-full bg-white transition-all duration-500\"\n          style={{ left: x, top: y, width: s, height: s, opacity: isDark ? 0.9 : 0, transform: `translateY(${isDark ? 0 : 6}px)`, transitionDelay: isDark ? `${120 + i * 50}ms` : \"0ms\" }} />\n      ))}\n      {/* cloud */}\n      <span className=\"absolute bottom-1.5 right-2 h-3 w-7 rounded-full bg-white/90 transition-all duration-500\"\n        style={{ opacity: isDark ? 0 : 1, transform: `translateY(${isDark ? 10 : 0}px)` }} />\n      <motion.span initial={false} animate={{ x: isDark ? 32 : 0 }} transition={SPRING}\n        className=\"absolute left-1 top-1 h-8 w-8 rounded-full\">\n        <span className={`absolute inset-0 rounded-full transition-colors duration-500 ${isDark ? \"bg-[#e8e6df]\" : \"bg-[#ffcf48]\"}`}\n          style={{ boxShadow: isDark ? \"inset -3px -3px 0 rgba(0,0,0,0.08)\" : \"0 0 0 4px rgba(255,214,90,0.35)\" }} />\n        <span className=\"absolute left-[9px] top-[7px] h-2 w-2 rounded-full bg-[#cfccc3] transition-opacity duration-500\" style={{ opacity: isDark ? 1 : 0 }} />\n        <span className=\"absolute left-[18px] top-[17px] h-1.5 w-1.5 rounded-full bg-[#cfccc3] transition-opacity duration-500\" style={{ opacity: isDark ? 1 : 0 }} />\n      </motion.span>\n    </button>\n  );\n}\n\nconst ROWS = [\n  { name: \"Sun and moon pill\", note: \"Two states, both icons always shown\" },\n  { name: \"Light, system, dark\", note: \"Three choices, follows the device\" },\n  { name: \"Icon button\", note: \"Compact, for a busy header\" },\n  { name: \"Animated switch\", note: \"A small scene that changes\" },\n];\n\nexport default function DarkModeToggleSwitch() {\n  const reduce = !!useReducedMotion();\n  const { pref, mode, setPref, flip } = useTheme(reduce);\n  const dark = mode === \"dark\";\n  const controls = [\n    <SunMoonPill key=\"a\" mode={mode} flip={flip} dark={dark} />,\n    <Segmented key=\"b\" pref={pref} setPref={setPref} dark={dark} />,\n    <IconButton key=\"c\" mode={mode} flip={flip} dark={dark} reduce={reduce} />,\n    <AnimatedSwitch key=\"d\" mode={mode} flip={flip} dark={dark} />,\n  ];\n\n  return (\n    <div className=\"min-h-[640px] bg-[#eef0f3] px-4 py-10 sm:px-8\" style={{ fontFamily: '\"Inter Tight\", Inter, ui-sans-serif, system-ui, sans-serif' }}>\n      {/* The preview area: everything inside switches with the chosen theme. */}\n      <section aria-labelledby=\"dmt-title\"\n        className={`mx-auto max-w-[760px] overflow-hidden rounded-2xl border shadow-[0_1px_2px_rgba(0,0,0,0.04),0_12px_40px_-12px_rgba(15,23,42,0.18)] transition-colors duration-500 ${dark ? \"border-zinc-800 bg-zinc-950 text-zinc-100\" : \"border-zinc-200 bg-white text-zinc-900\"}`}\n        style={{ colorScheme: mode }}>\n        <header className={`flex items-center justify-between gap-3 border-b px-5 py-4 transition-colors duration-500 sm:px-6 ${dark ? \"border-zinc-800\" : \"border-zinc-200\"}`}>\n          <div className=\"flex items-center gap-2.5\">\n            <span className=\"grid h-7 w-7 place-items-center rounded-lg bg-[#4F98FB] text-[13px] font-bold text-white\">F</span>\n            <span className=\"text-[15px] font-semibold tracking-tight\">Fieldnote</span>\n          </div>\n          <IconButton mode={mode} flip={flip} dark={dark} reduce={reduce} />\n        </header>\n\n        <div className=\"px-5 pb-6 pt-5 sm:px-6\">\n          <h2 id=\"dmt-title\" className=\"text-[20px] font-semibold tracking-tight\">Appearance</h2>\n          <p className={`mt-1 text-[14px] ${dark ? \"text-zinc-400\" : \"text-zinc-600\"}`} aria-live=\"polite\">\n            Showing <span className={dark ? \"text-zinc-100\" : \"text-zinc-900\"}>{mode}</span> mode\n            {pref === \"system\" ? \", following your device.\" : \".\"}\n          </p>\n\n          <ul className={`mt-5 divide-y rounded-xl border transition-colors duration-500 ${dark ? \"divide-zinc-800 border-zinc-800\" : \"divide-zinc-200 border-zinc-200\"}`}>\n            {ROWS.map((r, i) => (\n              <li key={r.name} className=\"flex flex-col gap-3 px-4 py-3.5 sm:flex-row sm:items-center sm:justify-between\">\n                <div className=\"min-w-0\">\n                  <p className=\"text-[14px] font-medium\">{r.name}</p>\n                  <p className={`text-[13px] ${dark ? \"text-zinc-400\" : \"text-zinc-600\"}`}>{r.note}</p>\n                </div>\n                <div className=\"shrink-0\">{controls[i]}</div>\n              </li>\n            ))}\n          </ul>\n        </div>\n      </section>\n    </div>\n  );\n}\n"}]}
