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. WriteCard({ title })that reads the theme and renders adivwith the classcard card-THEMEand anh3with the title. Appkeeps the theme (startinglight) in state, provides it, and renders abuttonwith the idtogglethat switches betweenlightanddark, and cards titledOne,TwoandThree.
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>
);
}