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 Answers1

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

LucasACH
  • 149
  • 6
  • 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 ? –  Apr 14 '21 at 21:32
  • Just updated my answer! Thought you wanted something simpler, but no problem, look for the live demo. – LucasACH Apr 15 '21 at 04:17
  • you could use some other Global state libraries like Recoil (i preffer it over context api) – SirHectorin Apr 15 '21 at 04:24
  • 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) –  Apr 15 '21 at 14:35
  • You can use any variable or function from your context by just importing them to your component like so: const {theme, changeTheme} = useContext(ThemeContext) – LucasACH Apr 15 '21 at 17:57