HomeOur TeamContact
React
How to create dark mode in react
Nisar
Nisar
May 03, 2023
1 min

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:

  1. Create a theme context:
import { createContext } from "react";

const ThemeContext = createContext();

export default ThemeContext;
  1. Create a theme provider:
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")
);
  1. Create a CSS file to define the light and dark themes:
/ *styles.css* /
body.light {
  background-color: #ffffff;
  color: #333333;
}

body.dark {
  background-color: #333333;
  color: #ffffff;
}
  1. Import the CSS file in your main App component and apply the theme:
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.


Previous Article
Inorder Tree Traversal with No Recursion
Nisar

Nisar

© 2023, All Rights Reserved.

Quick Links

Advertise with usAbout UsContact Us

Social Media