0

React beginner here, english is not my mother language sory for mistakes, i have been looking for setting dark mode on my website, examples what i have seen are mostly toggle between dark and light and you need to specify each colors inside those two. My point is how can i toggle between dark and light(this light should be my default colors set in css)

In my components each has its own css(own colors).If i want to have dark mode which toggles between dark and default css, for example changing background color, how would it be ?

my code:

import React, {useState, useEffect } from "react";

...

<div className="app">
      <Switch>
         <Route path="/a">
          <A />
        </Route>
        <Route path="/c">
          <C />
        </Route>
        <Route path="/b">
          <B />
        </Route>
        <Route path="/">
          <Redirect to="/a" />
        </Route>
      </Switch>
    </div>

if need more information, i can give.

1
  • You can use CSS variables to manage multiple themes. Commented Apr 14, 2021 at 14:21

1 Answer 1

1

You can use a context provider to globally use and update the darkMode state and the local storage to make it persistent on each session. Make sure to parse your data before setting a item into the local storage.

Here is a live demo

Sign up to request clarification or add additional context in comments.

5 Comments

When user clicks that toggle it should set my whole app to dark mode(there are many pages and things), in other examples they have used local storage and context api, we dont need those ?
Just updated my answer! Thought you wanted something simpler, but no problem, look for the live demo.
you could use some other Global state libraries like Recoil (i preffer it over context api)
could you possibly add to it multiple pages when user toggles dark mode it should change those other pages also to dark mode and if there is possibly some boxes(div) this toggle should change those to dark mode also (i want to know how to pass from one page to another this dark mode, if user toggles it should change all pages to dark mode and its content)
You can use any variable or function from your context by just importing them to your component like so: const {theme, changeTheme} = useContext(ThemeContext)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.