Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
833 B
3
Indexable
Never
import React, { createContext, useState, useContext } from "react";

// create a context with a default value
const ThemeContext = createContext("light");

function App() {
  const [theme, setTheme] = useState("light");

  const toggleTheme = () => {
    setTheme(theme === "light" ? "dark" : "light");
  };

  return (
    <ThemeContext.Provider value={theme}>
      <Header toggleTheme={toggleTheme} />
      <Content />
    </ThemeContext.Provider>
  );
}

function Header({ toggleTheme }) {
  const theme = useContext(ThemeContext);

  return (
    <header className={theme}>
      <h1>My App</h1>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </header>
  );
}

function Content() {
  const theme = useContext(ThemeContext);

  return <p className={theme}>This is the content of my app</p>;
}

export default App;