Change to a dark theme using React hooks in typescript

Hello, I am new to React and English is not my first language, so please excuse any mistakes. I have been trying to enable a dark mode feature on my website. Most examples I have found involve toggling between dark and light modes where you need to specify the colors for each mode. However, I want to toggle between dark mode and the default colors set in my CSS.

Each of my components has its own CSS with unique colors. If I want to implement a dark mode that switches the background color, how can I achieve this?

Here is a snippet of 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 you need more information, feel free to ask.

Answer №1

One way to create a global dark mode state is by using a context provider along with local storage for persistent storage across sessions. It's important to remember to properly parse your data before saving it to local storage to ensure accurate retrieval.

For a demonstration, check out this live demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for choosing the following row in an Angular user interface grid

How can I deselect the currently selected row and select the one that follows it by clicking a button? I am using AngularHotkeys.js for this purpose. It gets even more complicated because I can sort the table with different columns. It would be helpful to ...

Load different fonts dynamically based on environment configuration

My question is regarding loading multiple fonts from a font.css file in React. I need to make the font path dynamic based on the environment variables. Can anyone suggest a solution for achieving this? I've attempted to create a font.scss file and de ...

Incorporate an HTML code string into an Angular 2 template

I am working with HTML code stored in a Component variable, shown below: import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `Hi <div [innerHTML]="name"></div>`, styleUrls: [' ...

Tips for gracefully organizing a sequence of requests/callbacks with the dojo framework?

My experience with dojo has been pretty good, but I still have some questions about dojo.Deferred as there are features that I haven't fully explored yet. While researching, I began to wonder if using a Deferred in the following scenario would be a be ...

issue with eval() function

I am attempting to convert a JSON string from my .php file using the eval() function, but it is not working. The browser console shows a SyntaxError: expected expression, got '<'... However, when I comment out the line where eval() is used an ...

The issue with SetValue in mui Select and React hook form is causing problems

When the page loads, I would like to set the value initially. If needed, the value should be able to update as it is a multiSelect element. const options= [ { label: 'Apple', value: 'Apple' }, { label: 'Grape', value: &apo ...

intervals should not be attached after being cleared by a condition

I am facing an issue with my slider that has a play button to change the slide image and a pause button. When I click on play, it functions as intended. However, when I pause and try to play again, it does not work. Although I clear the interval using th ...

Adjusting HTML5 drag height while resizing the window

Code conundrum: var dragHeight = window.innerHeight - parseInt(jQuery("#drag_area").css("margin-top")) - 5;. It sets the drag height based on browser size, but there's a glitch. If I start with a non-maximized browser and then maximize it, the drag he ...

Error: Missing 1 type argument(s) in generic type definition

I've developed an abstract class structure as shown below: export abstract class CsvFileReader<T> { data: T[] = [] constructor(public file: string) {} abstract mapRow(row: string[]): T read() { this.data = this.file .split(& ...

Setting the minimum width for a grid item in a React Material UI component

Is there a way to ensure that a material-ui Grid item has a minimum width of 250 pixels? I've tried using the sizing suggestions from Material UI's documentation, but haven't had any success. The 'logo' element within the Grid cont ...

failure to properly assign a property during model update in mongoose

My BaseSchema contains logic that should set values for two properties when a new Model is created: schema.pre("save", function (next) { if (!schema.isNew) { this.createDate = new Date(); this.createBy = "kianoush"; } next(); }); If updating, ...

Error message encountered with React.js and Next.js: Attempting to iterate through a null object, resulting in a TypeError (property Symbol(Symbol.iterator

Having trouble accessing state's values using [...state_name,{}]. I'm facing an issue while trying to implement this algorithm for a dynamic menu. The data is fetched from the List action of the useFetch method. The data retrieval is successful ...

Using Angular 5 to access a variable within a component while iterating through a loop

I am currently in the process of transferring code from an AngularJS component to an Angular 5 component. Within my code, I have stored an array of objects in a variable called productlist. In my previous controller, I initialized another empty array nam ...

Issue: I am encountering a "Not Found" error when attempting to render the chart

"I keep encountering the Element not found error when using chart.render(). Removing the question mark fixes it temporarily, but upon page refresh, the same error reappears. Interestingly, adding back the question mark resolves the issue. However, occ ...

Styling Overlapping Divs with CSS3

I am attempting to replicate this particular effect using HTML within the UIWebView control on iOS. The desired outcome is to simulate a progress bar on the listing. My current approach involved utilizing this method, however, as you can observe, adding pa ...

How can Components be implemented across various Routes in React applications?

How can I implement Components on different routes in React? I attempted to achieve this with the following code, but I encountered an error: <Router> <App> <Route exact path='/signup' component={SignUp}/> ...

"Encountering an undefined error when making an AngularJS $http post request and receiving a

I am working on retrieving a specific value from the server side by passing a variable from the front-end (AngularJS javascript) to the backend (PHP) using $http. Once the server side (PHP) receives the value from the front-end, it executes an SQL query to ...

What is the best way to display a notification on the screen when a user fails to select an option from a checkbox in PHP?

I'm currently tackling a form project where I need to trigger an alert if the user hasn't selected any options from a checklist. Despite scouring various resources for solutions, my lack of JavaScript coding skills has left me at a standstill. He ...

Encountered a Building Error: "The type .... is included in the declarations of two modules: AppModule and Ionic."

As I strive to generate my APK for Android, I executed the following command: ionic cordova run android --prod --release Version of Ionic being used: Ionic V3 My app currently does not employ lazy loading (I confess I am not even sure how to go about th ...

What is the best way to incorporate an exception for the printThis() element?

Is there a way to exclude a specific div from being printed when using the printThis() function? For example: <div id="print-it"> <div>hello</div> <div id="no-print-this"> <button>must be show on page but not print</but ...