To create a dark mode in a React application, you can use React context and hooks to manage the theme state. This way, you can easily toggle between light and dark themes. Follow the steps below to implement dark mode:
import { createContext } from "react"; const ThemeContext = createContext(); export default ThemeContext;
import React, { useState } from "react"; import ThemeContext from "./ThemeContext"; const ThemeProvider = ({ children }) => { const \[theme, setTheme] = useState("light"); const toggleTheme = () => { setTheme((currentTheme) => (currentTheme === "light" ? "dark" : "light")); }; return ( <ThemeContext.Provider value={{ theme, toggleTheme }}> {children} </ThemeContext.Provider> ); }; export default ThemeProvider;
3 . Wrap your application with the ThemeProvider:
import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; import ThemeProvider from "./ThemeProvider"; ReactDOM.render( <React.StrictMode> <ThemeProvider> <App /> </ThemeProvider> </React.StrictMode>, document.getElementById("root") );
/ *styles.css* / body.light { background-color: #ffffff; color: #333333; } body.dark { background-color: #333333; color: #ffffff; }
import React, { useContext, useEffect } from "react"; import "./styles.css"; import ThemeContext from "./ThemeContext"; const App = () => { const { theme, toggleTheme } = useContext(ThemeContext); useEffect(() => { document.body.className = theme; }, \[theme]); return ( <div> <h1>React Dark Mode</h1> <button onClick={toggleTheme}>Toggle Theme</button> </div> ); }; export default App;
Now you have a simple React application with a toggle button to switch between light and dark modes. The theme state is managed by the ThemeProvider, and the current theme is applied to the body element using the useEffect hook.
Quick Links
Legal Stuff