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

The process of converting a response into an Excel file

After sending a request to the server and receiving a response, I am struggling with converting this response into an Excel file. Response header: Connection →keep-alive cache-control →no-cache, no-store, max-age=0, must-revalidate content-dispositio ...

Posting a string using AJAX to the Java backend through JavaScript

I'm currently working on a comment section for a Web Client. There are two tables involved - one for the comments and another for the users. My goal is to send input data from HTML <input> tags to a Java Service where the data will be processed ...

What is the best way to modify the font color of DialogTitle and DialogContent in Material UI within a react.js environment?

Is there a way to customize the font/text color in DialogTitle and DialogContent components using Material UI in react.js? I have successfully changed the background color for the Dialog, but it seems changing the font color for Dialog and DialogContent i ...

Is the jQuery AJAX call using POST method being retrieved as $_GET?

Below is a snippet of code that I've successfully implemented: <script type="text/javascript"> $(document).ready(function() { // Initializing the table $('#table_1').tableDnD({ onDrop: function(table, row) { $.tab ...

Encountering a 403 error while attempting to install Meteor with npm using the command npm install -

Following the installation instructions provided on the official Meteor website at , I encountered an error while trying to install Meteor using the command "npm install -g meteor". Here is the detailed error message: os  win 10 pro node -v  v14.15.1 n ...

Shifting HTML table in Javascript by toggling checkboxes

When I click the checkbox, the table elements are not displaying inline. I am simply hiding the class "box". Do I need to write a special format? By default, the elements are displayed inline but when I check the checkbox, they shift. The column 'Stat ...

I am looking to narrow down the Google Places autocomplete suggestions specifically for India within Next Js

In my current project developed with Next.js, I am utilizing the react-places-autocomplete package to enhance user experience. One specific requirement I have is to filter out location suggestions for India only, excluding all other countries. Despite att ...

Combine several objects into one consolidated object

Is there a way to combine multiple Json objects into one single object? When parsing an array from AJAX, I noticed that it logs like this: 0:{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support", ...} 1:{id: "25", user: "Jim ...

Can a JavaScript or jQuery function be triggered on input change to perform a PHP call to check a database?

Is it possible to implement live form validation without a page reload? I am looking to add a function like the one below: <input onchange="validate();"></input> function validate() { // PHP here to check input value against table value o ...

Is there a way to rearrange the tabs so that the first tab is at

Is there a way for me to align with the others without being stuck below #first_tab in the code? I'm having trouble figuring it out on this website: Your assistance would be greatly appreciated! Thank you in advance! CSS Code: #first_tab { ...

Guide on implementing two submission options in an HTML form using JavaScript

Currently, I am working on a form that includes two buttons for saving inputted data to different locations. However, I am facing an issue with the functionality of the form when it comes to submitting the data. Since only one submit function can be activa ...

Display exclusively the chosen option from the dropdown menu

I am facing an issue with the select input on my webpage. Whenever I try to print the page, it prints all the options of the select instead of just the one that is selected. Can someone please guide me on how to modify it so that only the selected option ...

Creating a table and populating its cells with values all within the confines of a single function

This section of code aims to create 3 arrays by extracting values inputted by the user from a popup menu in the HTML file. These values are then utilized to populate the table displayed below. var arrM = new Array; var arrT = new Array; var ar ...

Exporting Arrays in Ionic Angular with Typescript is an essential feature

When trying to access an exported component in Typescript, there may be issues with importing the module correctly into another component. An error message is displayed when calling the AddToArray method: Cannot read property 'push' of undefi ...

Combining two input text strings

A React component I'm working on takes the user's first and last name to create unique usernames for them. class App extends Component { render() { return ( <div className="App"> First name:<br/> <input ...

Remove any words that are not included in the specified list

Here is the code snippet to achieve the desired functionality: const { words } = require("../../json/words.json") const args = message.content.split(' ') const wordss = words.filter(m=> m.includes(args)) if(args > 1 || !wordss) { ...

Adjust the active carousel item to 0 within onsen-ui (displaying a list of carousel items in a sliding menu)

In my sliding menu, each menu item contains a carousel with two items. I am trying to make the first carousel item show after closing and reopening the menu, or by clicking a button outside of the list on the menu page. This is my current setup: <ons- ...

How can real-time data be fetched or connected to Firebase v9 in the onSubmit function?

Please provide the code in firebase-v9 to fetch the onSubmit function from firestore: const onSubmit = (formData) => { console.log(formData) db.collection('emails').add({ to: formData.to, subject: formData.subject, message: formData.mess ...

Exploring objects as strings to retrieve data with Javascript

In a scenario where I receive an object of varying length that I do not control, I am required to extract specific data from it. The response I receive is in the form of a formatted string: { "questionId": 18196101, "externalQuestionId": "bcc38f7 ...

Steps to successfully set up a React application without encountering any installation errors

Hey everyone, I've been trying to install React on my system for the past two days but keep encountering errors. Initially, I used the commands below to install the React app and it worked smoothly: 1. npm install -g create-react-app 2. create-react- ...