universal-theme

0
0
Source

Configure light/dark/system theme handling across iOS, Android, and Web with universal CSS

Install

mkdir -p .claude/skills/universal-theme && curl -L -o skill.zip "https://mcp.directory/api/skills/download/6395" && unzip -o skill.zip -d .claude/skills/universal-theme && rm skill.zip

Installs to .claude/skills/universal-theme

About this skill

Universal Theme Handling for Expo

This guide covers implementing proper light/dark/system theme handling across all platforms while respecting web static rendering. This is specifically for projects using universal CSS (Tailwind v4 + react-native-css).

Overview

The approach uses:

  • CSS color-scheme - For automatic system preference detection via prefers-color-scheme
  • CSS classes (.light/.dark) - For manual theme override (shadcn/ui pattern)
  • React Native Appearance API - For native platform theme control
  • ThemeContextProvider - Unified React context for theme state management
  • ThemeScript - Inline script to prevent flash of incorrect theme (FOUC) on page load
  • localStorage persistence - Theme preference persists across sessions
  • Cross-tab sync - Theme changes sync across browser tabs

CSS Setup

Theme Control in CSS

Update your CSS file (e.g., src/css/sf.css) to use color-scheme for automatic system preference detection:

@layer base {
  /*
   * Theme handling with light-dark() CSS function
   * https://lightningcss.dev/transpilation.html#light-dark
   *
   * By default, use "light dark" which enables automatic switching based on
   * prefers-color-scheme media query (system preference).
   *
   * Use .light or .dark class on html/body to force a specific theme.
   * This follows the shadcn/ui pattern for theme control.
   */
  html {
    color-scheme: light dark;
  }

  /* Force light mode when .light class is applied */
  html.light,
  .light {
    color-scheme: light;
  }

  /* Force dark mode when .dark class is applied */
  html.dark,
  .dark {
    color-scheme: dark;
  }
}

Using light-dark() for Colors

Define CSS variables that automatically switch based on the resolved color scheme:

:root {
  /* Colors automatically switch based on color-scheme */
  --sf-text: light-dark(rgb(0 0 0), rgb(255 255 255));
  --sf-bg: light-dark(rgb(255 255 255), rgb(0 0 0));
  --sf-blue: light-dark(rgb(0 122 255), rgb(10 132 255));
}

When color-scheme: light dark is set (system mode), light-dark() responds to the user's system preference automatically via prefers-color-scheme media query.

Theme Context Provider

Create a theme context that manages light/dark/system modes across platforms.

Types

// src/components/ui/theme-context.tsx

/**
 * Theme mode values:
 * - "system": Use the system's color scheme (default)
 * - "light": Force light mode
 * - "dark": Force dark mode
 */
export type ThemeMode = "system" | "light" | "dark";

/**
 * Resolved theme is always either "light" or "dark"
 */
export type ResolvedTheme = "light" | "dark";

interface ThemeContextValue {
  /** The current theme mode setting (system/light/dark) */
  mode: ThemeMode;
  /** The resolved theme based on mode and system preference */
  resolvedTheme: ResolvedTheme;
  /** Set the theme mode */
  setMode: (mode: ThemeMode) => void;
  /** Whether the resolved theme is dark */
  isDark: boolean;
}

localStorage Persistence

Persist theme preference to localStorage so it survives page reloads:

const STORAGE_KEY = "theme-mode";

function getStoredTheme(): ThemeMode | null {
  if (process.env.EXPO_OS !== "web") return null;
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored === "light" || stored === "dark" || stored === "system") {
      return stored;
    }
  } catch {
    // localStorage unavailable
  }
  return null;
}

function saveTheme(mode: ThemeMode): void {
  if (process.env.EXPO_OS !== "web") return;
  try {
    localStorage.setItem(STORAGE_KEY, mode);
  } catch {
    // localStorage unavailable
  }
}

Transition Disabling (borrowed from next-themes)

Temporarily disable CSS transitions during theme changes to prevent jarring animations:

function disableTransitions(): () => void {
  if (process.env.EXPO_OS !== "web") return () => {};

  const style = document.createElement("style");
  style.appendChild(
    document.createTextNode(
      "*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}"
    )
  );
  document.head.appendChild(style);

  return () => {
    // Force a reflow to ensure transitions are disabled before cleanup
    (() => window.getComputedStyle(document.body))();
    setTimeout(() => {
      document.head.removeChild(style);
    }, 1);
  };
}

Web Theme Application

On web, apply .light or .dark classes to the <html> element. For system mode, remove both classes to let CSS handle it via prefers-color-scheme:

function applyWebTheme(mode: ThemeMode, disableAnimations = false): void {
  if (process.env.EXPO_OS !== "web") return;

  const enableTransitions = disableAnimations ? disableTransitions() : null;

  const html = document.documentElement;

  // Remove existing theme classes
  html.classList.remove("light", "dark");

  // Apply appropriate class based on mode
  if (mode === "light") {
    html.classList.add("light");
  } else if (mode === "dark") {
    html.classList.add("dark");
  }
  // For "system" mode, no class is needed - CSS will use prefers-color-scheme

  enableTransitions?.();
}

Native Theme Application

On iOS and Android, use React Native's Appearance.setColorScheme() API:

import { Appearance, ColorSchemeName } from "react-native";

function applyNativeTheme(mode: ThemeMode): void {
  if (process.env.EXPO_OS === "web") return;

  // Map theme mode to ColorSchemeName (null = system)
  const colorScheme: ColorSchemeName = mode === "system" ? null : mode;

  if (process.env.EXPO_OS === "ios") {
    // On iOS, delay slightly to allow for smooth animations
    setTimeout(() => {
      Appearance.setColorScheme(colorScheme);
    }, 100);
  } else {
    // On Android, apply immediately
    Appearance.setColorScheme(colorScheme);
  }
}

Full Context Provider Implementation

import React, {
  createContext,
  useState,
  useEffect,
  useCallback,
  useMemo,
  use,
} from "react";
import { Appearance, ColorSchemeName, useColorScheme } from "react-native";

const ThemeContext = createContext<ThemeContextValue | null>(null);

export function useTheme(): ThemeContextValue {
  const context = use(ThemeContext);
  if (!context) {
    throw new Error("useTheme must be used within a ThemeContextProvider");
  }
  return context;
}

interface ThemeContextProviderProps {
  children: React.ReactNode;
  /** Initial theme mode, defaults to "system" */
  defaultMode?: ThemeMode;
}

export function ThemeContextProvider({
  children,
  defaultMode = "system",
}: ThemeContextProviderProps) {
  // Initialize from localStorage on web, otherwise use defaultMode
  const [mode, setModeState] = useState<ThemeMode>(() => {
    if (process.env.EXPO_OS === "web") {
      return getStoredTheme() ?? defaultMode;
    }
    return defaultMode;
  });

  // Get the current system color scheme
  const systemColorScheme = useColorScheme();

  // Resolve the actual theme based on mode and system preference
  const resolvedTheme: ResolvedTheme = useMemo(() => {
    if (mode === "system") {
      return systemColorScheme === "dark" ? "dark" : "light";
    }
    return mode;
  }, [mode, systemColorScheme]);

  const isDark = resolvedTheme === "dark";

  // Apply theme when mode changes
  const setMode = useCallback((newMode: ThemeMode) => {
    setModeState(newMode);
    saveTheme(newMode);

    if (process.env.EXPO_OS === "web") {
      // Disable transitions when user explicitly changes theme
      applyWebTheme(newMode, true);
    } else {
      applyNativeTheme(newMode);
    }
  }, []);

  // Apply initial theme on mount
  useEffect(() => {
    if (process.env.EXPO_OS === "web") {
      applyWebTheme(mode);
    } else {
      applyNativeTheme(mode);
    }
  }, []);

  // Cross-tab synchronization via storage events (web only)
  useEffect(() => {
    if (process.env.EXPO_OS !== "web") return;

    const handleStorage = (e: StorageEvent) => {
      if (e.key !== STORAGE_KEY) return;

      const newMode = e.newValue as ThemeMode | null;
      if (newMode === "light" || newMode === "dark" || newMode === "system") {
        setModeState(newMode);
        applyWebTheme(newMode, true);
      } else {
        // Invalid or cleared - reset to default
        setModeState(defaultMode);
        applyWebTheme(defaultMode, true);
      }
    };

    window.addEventListener("storage", handleStorage);
    return () => window.removeEventListener("storage", handleStorage);
  }, [defaultMode]);

  const value = useMemo(
    () => ({
      mode,
      resolvedTheme,
      setMode,
      isDark,
    }),
    [mode, resolvedTheme, setMode, isDark]
  );

  return <ThemeContext value={value}>{children}</ThemeContext>;
}

Theme Provider with React Navigation

Wrap the theme context with React Navigation's theme provider for proper navigation theming:

// src/components/ui/theme-provider.tsx
import {
  DarkTheme,
  DefaultTheme,
  ThemeProvider as RNTheme,
} from "@react-navigation/native";
import { ThemeContextProvider, useTheme, ThemeScript } from "./theme-context";

// Re-export for convenience
export { useTheme, ThemeScript } from "./theme-context";
export type { ThemeMode, ResolvedTheme } from "./theme-context";

function NavigationThemeProvider({ children }: { children: React.ReactNode }) {
  const { isDark } = useTheme();
  return (
    <RNTheme value={isDark ? DarkTheme : DefaultTheme}>{children}</RNTheme>
  );
}

export default function ThemeProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <ThemeContextProvider defaultMode="system">
      <NavigationThemeProvider>{children}</NavigationThemeProvider>
    </ThemeContextProvider>
  );
}

Preventing Flash of Incorrect Theme (FOUC)

On page load, there can be a brief flash where the wrong the


Content truncated.

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.