Theme Toggle

Add a light/dark toggle button to your site in under a minute. Works with React or plain JS.

Preview

Click the toggles below to see them in action. Each mini-preview has its own independent theme state.

My App
DashboardSettings
Icon Button
My App
DashboardSettings
Pill Switch

Size Variants

Small
Medium
Large

React

Drop the NightfallToggle component anywhere inside your NightfallProvider:

Header.tsx
import { NightfallToggle } from 'nightfall-css/react'

export function Header() {
  return (
    <header className="flex items-center justify-between p-4">
      <h1>My App</h1>
      <NightfallToggle />
    </header>
  )
}

Customise with props:

  • size "sm" | "md" | "lg" (default: "md")
  • iconStyle "system" | "emoji" | "text" (default: "system")
  • className — Additional classes for custom styling

Build Your Own (React)

Use the useNightfall hook to build a fully custom toggle:

CustomToggle.tsx
import { useNightfall } from 'nightfall-css/react'

export function CustomToggle() {
  const { resolvedTheme, toggleTheme } = useNightfall()

  return (
    <button onClick={toggleTheme} aria-label="Toggle theme">
      {resolvedTheme === 'dark' ? '☀️' : '🌙'}
    </button>
  )
}

Vanilla JS

For non-React projects, inject a pre-built toggle button with one function call:

index.html
<div id="toggle-container"></div>

<script type="module">
  import {
    createToggle,
    getToggleHTML,
    getToggleCSS
  } from 'nightfall-css/script'

  // 1. Inject the toggle CSS
  const style = document.createElement('style')
  style.textContent = getToggleCSS()
  document.head.appendChild(style)

  // 2. Inject the toggle button
  document.querySelector('#toggle-container')
    .innerHTML = getToggleHTML()

  // 3. Wire up the toggle logic
  const { toggle } = createToggle()
  document.querySelector('#nightfall-toggle')
    .addEventListener('click', toggle)
</script>

Styling

The built-in toggle uses the .nightfall-toggle class. Override it to match your design:

custom-toggle.css
/* Override size and color */
.nightfall-toggle {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  color: var(--nf-text);
}

.nightfall-toggle:hover {
  background: var(--nf-surface);
}

/* Icon visibility is handled automatically:
   - Sun icon shows in dark mode
   - Moon icon shows in light mode */

Keyboard Accessible

Both the React component and the vanilla HTML toggle include proper accessibility out of the box:

  • aria-label="Toggle theme" for screen readers
  • Focusable with Tab and activatable with Enter / Space
  • Visible focus ring for keyboard navigation