Command Palette

Search for a command to run...

Hectal
Phase 22: Architecture and Patterns
React · Exercise 1 of 5Next
Intermediate

A switch that works controlled and uncontrolled

The Switch component only keeps its own state, so the parent can't control it. Make it support both modes, like a native input: checked + onCheckedChange (controlled) and defaultChecked (uncontrolled).

Rule: if checked is not undefined, the switch shows checked and only calls onCheckedChange(next) on click. Otherwise it keeps its own state (starting from defaultChecked) and also calls onCheckedChange if given.

Keep the ids and aria-checked as they are: #wifi is uncontrolled, #dark is controlled by App, #status shows the parent's value and #reset sets dark mode back on.

What Check tests

  1. The uncontrolled Wi-Fi switch starts off and turns on when clicked
  2. The controlled dark-mode switch starts on, because the parent says so
  3. Clicking dark mode updates the parent's status
  4. The parent's Reset button changes the switch

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.