React: Cards that read the theme

Provide a theme once and let every card read it.

What to build

A theme switch and three cards styled by context.

Requirements

  • Create ThemeContext. Write Card({ title }) that reads the theme and renders a div with the class card card-THEME and an h3 with the title.
  • App keeps the theme (starting light) in state, provides it, and renders a button with the id toggle that switches between light and dark, and cards titled One, Two and Three.

Constraints

Do not pass the theme to Card as a prop.

Example

After one click all three cards have the class "card card-dark".

Why it works

Every card reads the same provided value, so switching the state in App updates them all without touching the props in between.

Hints

Hint 1

const ThemeContext = createContext("light"); and useContext(ThemeContext) inside Card.

Hint 2

App keeps the theme in state and provides it around the cards.

Solution

Show one correct solution (try it yourself first)
import { createContext, useContext, useState } from "react";

const ThemeContext = createContext("light");

function Card({ title }) {
  const theme = useContext(ThemeContext);
  return (
    <div className={"card card-" + theme}>
      <h3>{title}</h3>
    </div>
  );
}

export default function App() {
  const [theme, setTheme] = useState("light");
  return (
    <ThemeContext value={theme}>
      <button id="toggle" onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
        Switch
      </button>
      <Card title="One" />
      <Card title="Two" />
      <Card title="Three" />
    </ThemeContext>
  );
}

Lesson: Context: sharing values across the tree →