Command Palette

Search for a command to run...

Hectal
Phase 24: Frontend Patterns You'll Build Everywhere
React · Exercise 1 of 6Next
Intermediate

A theme switcher that follows the system

The CSS already defines colour variables for light and dark, switched by data-theme="dark" on <html>. The <select id="theme"> changes state, but nothing happens on screen.

Make the page show the chosen theme: put data-theme="light" or data-theme="dark" on document.documentElement. When the choice is system, follow matchMedia("(prefers-color-scheme: dark)").

Save the choice in localStorage under the key theme, and start from the saved choice when the page loads (default system).

What Check tests

  1. Choosing Dark sets data-theme="dark" on <html>
  2. The page background uses the dark colour
  3. The choice is saved in localStorage as "theme"
  4. System follows prefers-color-scheme
  5. The saved choice is read on start

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.