Skip to content

Tactile Theme Toggle

Switch between light and dark with a tactile switch that shows a sun or moon icon.

Preview

Examples

Theme transition

A slide transition declared on this control. Duration is 500 milliseconds. Other controls keep their own settings.

When to use

  • Use a physical, on/off switch for light and dark mode.
  • Use a control that shows the current mode on its thumb: a sun for light and a moon for dark.

When not to use

  • People need to choose the system preference. Use Theme Switcher or Theme Selector.
  • The control changes a palette. Use Color Theme Selector.

Installation

Set up uitheme-web in an existing Tailwind app. Then install the component. The control has no primitive dependency. It uses Lucide icons and reuses the shared cn utility.

Tailwind version
Source language
npx uitheme-cli add tactile-theme-toggle --base radix --tailwind 4 --language ts

To install with shadcn, first add the UI-Theme registry to components.json.

npx shadcn@latest add @uitheme/tactile-theme-toggle

Usage

Use the control inside your theme provider. Import it from your app’s component directory.

example.tsx
'use client';

import { UIThemeProvider } from 'uitheme-web/react';
import { TactileThemeToggle } from '@/components/ui/tactile-theme-toggle';

export function Example() {
  return (
    <UIThemeProvider>
      <TactileThemeToggle />
    </UIThemeProvider>
  );
}

API reference

These props belong to the installed control. Its page transition settings override the provider for this action only.

PropTypeBehavior
labelstringOverride the readable accessible label.
classNamestringExtend the root styles. Your classes replace default classes through the local merge helper.
classesobjectStyle the root, track, and thumb parts.
disabledbooleanDisable interaction. Preference controls also wait for the provider to mount.
animationTypeThemeAnimationTypeOverride the UI theme transition for this control. Defaults to the provider setting.
durationnumberUI theme transition duration in milliseconds. Defaults to the provider setting.
slideDirectionSlideDirectionValid only with animationType set to ThemeAnimationType.SLIDE. Other animation types do not accept this prop.

Keyboard

KeyAction
Enter / SpaceToggle the resolved light/dark theme. Keyboard activation changes the theme without the page animation.

Accessibility

  • The control is a button with role="switch". aria-checked is true in dark mode.
  • The default accessible label is “Dark theme”. If you change it, name the checked state, not the action.
  • The track, thumb, and icons are decorative and hidden from assistive technology.
  • The control stays disabled until the theme provider mounts.
  • Reduced motion removes the icon rotation and scale. The thumb travel and the icon fade take 120ms.
  • In forced-colors mode, the control keeps a visible border.

Theme behavior

The switch is off in resolved light mode and on in resolved dark mode. The thumb shows a sun in light mode and a moon in dark mode. All colors come from your theme tokens, so the switch follows the active color palette. Activation replaces a system preference with the opposite resolved theme. The clicked switch sets the page transition origin.

AI Agent notes

  • Use uitheme-web/react for React or uitheme-web/vue for Vue. Keep the theme provider around the control.
  • Keep page transitions in the control’s animationType and duration props. Do not add a standalone transition-settings control.
  • Use the shared theme tokens. Do not hardcode a color. The track uses bg-input when off and bg-primary when on. The thumb uses bg-background and text-muted-foreground.
  • Keep role="switch", aria-checked, the label, focus styles, the disabled state, and reduced-motion behavior when you edit the source.
  • All sizes use em. Change the size with a font-size class on the root, not with fixed widths.

Source

The CLI reuses your shared cn utility. If it is missing, installation creates it at the configured utils path. Existing utilities are checked before a replacement is offered.

These are the files the CLI installs. The control installs one main component file.

'use client';

import * as React from 'react';
import { SunIcon, MoonIcon } from 'lucide-react';
import type { Theme, ThemeControlTransitionProps } from 'uitheme-web/react';
import { useUITheme } from 'uitheme-web/react';
import { cn } from '@/lib/utils';

export type TactileThemeToggleClasses = {
  root?: string;
  track?: string;
  thumb?: string;
};

export type TactileThemeToggleProps = Omit<
  React.ComponentPropsWithoutRef<'button'>,
  'className' | 'children' | 'onClick' | 'value' | 'role' | 'aria-checked'
> &
  ThemeControlTransitionProps & {
    onClick?: React.MouseEventHandler<HTMLButtonElement>;
    className?: string;
    classes?: TactileThemeToggleClasses;
    label?: string;
    disabled?: boolean;
  };

const icon =
  'col-start-1 row-start-1 size-[0.875em] transition-[transform,opacity,rotate,scale] duration-[220ms] ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:!transform-none motion-reduce:!rotate-0 motion-reduce:!scale-100 motion-reduce:duration-[120ms]';

export const TactileThemeToggle = React.forwardRef<
  HTMLButtonElement,
  TactileThemeToggleProps
>(function TactileThemeToggle(
  {
    animationType,
    duration,
    slideDirection,
    className,
    classes,
    label = 'Dark theme',
    disabled = false,
    onClick,
    ...buttonProps
  },
  forwardedRef
) {
  const { resolvedTheme, switchTheme, mounted } = useUITheme();
  const dark = resolvedTheme === 'dark';
  const target: Theme = dark ? 'light' : 'dark';

  return (
    <button
      {...buttonProps}
      ref={forwardedRef}
      type="button"
      role="switch"
      aria-checked={dark}
      aria-label={label}
      data-state={dark ? 'checked' : 'unchecked'}
      disabled={disabled || !mounted}
      className={cn(
        'relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-[0.5em] border border-border bg-muted p-[0.125em] text-[1.5em] shadow-sm outline-none [-webkit-tap-highlight-color:transparent] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50 forced-colors:border-[ButtonText]',
        classes?.root,
        className
      )}
      onClick={(event) => {
        onClick?.(event);

        if (!event.defaultPrevented)
          void switchTheme(target, {
            element: event.currentTarget,
            animationType,
            duration,
            slideDirection,
            animationOff: event.detail === 0,
          });
      }}
    >
      <span
        aria-hidden="true"
        className={cn(
          'relative flex h-[1.5em] w-[3em] items-center rounded-[0.375em] shadow-inner transition-colors duration-200 ease-out motion-reduce:duration-[120ms]',
          dark ? 'bg-primary' : 'bg-input',
          classes?.track
        )}
      >
        <span
          className={cn(
            'absolute left-[0.0625em] flex size-[1.375em] items-center justify-center rounded-[0.3125em] bg-background text-muted-foreground shadow-sm transition-[transform,translate] duration-[220ms] ease-[cubic-bezier(0.32,0.72,0,1)] will-change-transform motion-reduce:duration-[120ms]',
            dark ? 'translate-x-[1.5em]' : 'translate-x-0',
            classes?.thumb
          )}
        >
          <span className="grid">
            <SunIcon
              focusable="false"
              strokeWidth={2.25}
              className={cn(
                icon,
                dark ? '-rotate-90 scale-50 opacity-0' : 'opacity-100'
              )}
            />
            <MoonIcon
              focusable="false"
              strokeWidth={2.25}
              className={cn(
                icon,
                dark ? 'opacity-100' : 'rotate-90 scale-50 opacity-0'
              )}
            />
          </span>
        </span>
      </span>
    </button>
  );
});

Dependencies: lucide-react

Customization

The default size is text-[1.5em] on the root. Set another font size through className or classes.root to scale the switch, for example text-base.

Use classes.track and classes.thumb to restyle those parts. Your classes replace default classes through the local merge helper.

Use slideDirection only when animationType is ThemeAnimationType.SLIDE. Set both props on the control when you need a slide direction override.