← Back to React Course | Chapter 11: Styling in React | Lesson 6 of 8

Theming और Dark Mode

Theming ऐसा है जैसे अपने app को एक costume closet देना — एक switch flip करें और सब कुछ daytime colors से nighttime colors में बदल जाता है, scratch से कुछ भी redesign किए बिना।
Syntax
markup
const ThemeContext = createContext();

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("light");
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <div className={theme}>{children}</div>
    </ThemeContext.Provider>
  );
}

Current Theme को Context में Store करना

एक ThemeContext, जो current theme name (जैसे light या dark) और इसे बदलने का एक function रखता है, app में किसी भी component को current theme पढ़ने और react करने देता है, हर जगह props के through manually इसे pass किए बिना।

Note: इसे earlier वाले useLocalStorage pattern के साथ pair करें ताकि chosen theme page reload में survive करे।
Warning: Theme value पढ़ना automatically कुछ भी restyle नहीं करता — components को अब भी इसका actually उपयोग करना होगा अपनी appearance बदलने के लिए।

उदाहरण: Storing the Current Theme in Context

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
const ThemeContext = React.createContext();
function ThemeProvider({ children }) {
  const [theme, setTheme] = React.useState("light");
  return <ThemeContext.Provider value={{ theme, setTheme }}>{children}</ThemeContext.Provider>;
}
function ThemedBox() {
  const { theme } = React.useContext(ThemeContext);
  return <div style={{ background: theme === "dark" ? "#222" : "#fff", color: theme === "dark" ? "#fff" : "#000", padding: "16px" }}>Current theme: {theme}</div>;
}
function App() {
  return <ThemeProvider><ThemedBox /></ThemeProvider>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Themes के बीच Toggle करना

एक toggle button context से current theme पढ़ता है और opposite value के साथ setTheme call करता है, user को demand पर themes switch करने देते हुए। useContext के through theme पढ़ने वाला हर component नई value के साथ automatically re-render होता है।

Note: Theme toggle button को कहीं globally visible जगह रखें, जैसे एक header, ताकि users इसे आसानी से ढूंढ सकें।
Warning: अगर कई components independently theme पढ़ते हैं, तो एक theme change उन सबको re-render करवाता है — theme toggling जैसे rare action के लिए acceptable, लेकिन जानने लायक।

उदाहरण: Toggling Between Themes

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
const ThemeContext = React.createContext();
function ThemeProvider({ children }) {
  const [theme, setTheme] = React.useState("light");
  const toggle = () => setTheme(t => t === "light" ? "dark" : "light");
  return <ThemeContext.Provider value={{ theme, toggle }}>{children}</ThemeContext.Provider>;
}
function ThemeToggle() {
  const { theme, toggle } = React.useContext(ThemeContext);
  return <button onClick={toggle}>Switch to {theme === "light" ? "dark" : "light"} mode</button>;
}
function App() {
  return <ThemeProvider><ThemeToggle /></ThemeProvider>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Theme Values के लिए CSS Variables उपयोग करना

हर component में JavaScript ternaries से colors compute करने के बजाय, CSS custom properties (variables) एक बार define की जा सकती हैं और document root पर swap की जा सकती हैं, plain CSS rules को उन्हें हर जगह automatically pick up करने देते हुए जहां वे उपयोग होती हैं।

Note: document.documentElement.style पर variables set करना (या वहां एक class toggle करना) एक single change को var(--color-name) उपयोग करने वाले हर component तक cascade करने देता है।
Warning: CSS variables का actually reference होना ज़रूरी है आपके stylesheets में (var(--name) के through) कोई effect होने के लिए — उन्हें define करना अकेले visually कुछ नहीं बदलता।

उदाहरण: Using CSS Variables for Theme Values

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function App() {
  const [dark, setDark] = React.useState(false);
  const vars = dark ? { "--bg": "#222", "--fg": "#fff" } : { "--bg": "#fff", "--fg": "#000" };
  return (
    <div style={{ ...vars, background: "var(--bg)", color: "var(--fg)", padding: "16px" }}>
      <button onClick={() => setDark(!dark)}>Toggle theme (CSS variables)</button>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Theme variables reference करने के बजाय components में colors directly hardcode करना, जिससे बाद में theme switch करने के लिए हर component edit करना पड़ता है।
  2. User की theme choice persist न करना (जैसे localStorage में), इसलिए यह हर page reload पर reset हो जाती है।
  3. Individual components के बाहर की चीज़ें भी update करना भूल जाना, जैसे page का overall background color।
चैप्टर सारांश
  • Theming एक app को shared variables उपयोग करके visual variants (जैसे light/dark mode) के बीच switch करने देती है hardcoded values के बजाय।
  • एक common approach Context (current theme रखने के लिए) को CSS variables या एक theme object के साथ combine करता है।
  • Chosen theme persist करना (जैसे localStorage) इसे page reloads में consistent रखता है।
  • CSS custom properties (variables) को document root पर swap किया जा सकता है पूरे app को एक साथ restyle करने के लिए।
ब्राउज़र सपोर्ट

CSS custom properties सभी modern browsers में supported हैं; Context API React 16.3 से stable है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.