DEV Community

CHENER ZHANG
CHENER ZHANG

Posted on

4 1

Change Dark theme React

I read a lots article of writing a toggle to change the theme. For a beginner, this is entire too difficult to understand multiple files and code.

I'm going to show you guys a simple way to change the by using useState and styled-components πŸ˜› 😝

Here is my step:

Step 1 :

Install styled-components, we need this library.

npm install --save styled-components
Enter fullscreen mode Exit fullscreen mode

Step 2:
Import these things, you will use useState later 😏

import { ThemeProvider } from "styled-components";
import { createGlobalStyle } from "styled-components";
import { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

Step 3:
Initialize the Dark and Light
Simply define our lovely variable πŸ˜›:


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

  const light = {
    body: "#E2E2E2" // you can change to any color you like
  };

  const dark = {
    body: "#363537" // you can change to any color you like
  };

  const GlobalStyle = createGlobalStyle`
  body{
    background: ${({ theme }) => theme.body};
  }
  `;

Enter fullscreen mode Exit fullscreen mode

Step 4:
Return


import "./styles.css";
import { ThemeProvider } from "styled-components";
import { createGlobalStyle } from "styled-components";
import { useState } from "react";

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

  const light = {
    body: "#E2E2E2"
  };
  const dark = {
    body: "#363537"
  };

  const GlobalStyle = createGlobalStyle`
  body{
    background: ${({ theme }) => theme.body};
  }
  `;

  return (
    <ThemeProvider theme={theme === "light" ? dark : light}>
      <GlobalStyle />
      <button
        onClick={() => {
          if (theme === "light") {
            setTheme("dark");
          } else {
            setTheme("light");

          }
        }}
      >
        change
      </button>
    </ThemeProvider>
  );
}

Enter fullscreen mode Exit fullscreen mode

Here is a demo:

demo

Hope these help you, Thanks for reading, Have fun! πŸ₯°

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs