Switch between using the useState hook by toggling it with the MUI Switch

Looking to implement a custom Dark Mode feature for a specific element on my create-react-app website using MUI. I have successfully implemented the Switch to change the state on toggle, but I am having trouble figuring out how to toggle it back and forth. I basically want the page to switch to dark mode when toggled and revert back to light mode with the same toggle button. Any suggestions would be appreciated.

import React from 'react'
import Switch from '@mui/material/Switch';


const DarkMode = () => {
    const [color, setColor] = React.useState(false)
  return (
    <div style={{ backgroundColor: color ? '#2c2d30' : '#ffffff' }}>
        <Switch onChange={setColor} />
        <h1 style={{ color: color ? '#ffffff' : '#000000' }}>Hello welcome to my site</h1>
    </div>
  )
}

export default DarkMode

Answer №1

const LightDarkMode = () => {
    const [theme, setTheme] = React.useState(false)

    const toggleTheme = () =>{
      setTheme(!theme);
    }
  return (
    <div style={{ backgroundColor: theme ? '#333' : '#fff' }}>
        <Switch onChange={toggleTheme} />
        <h1 style={{ color: theme ? '#fff' : '#000' }}>Change Theme</h1>
    </div>
  )
}

export default LightDarkMode

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

Issue with AJAX request on Internet Explorer versions 8 and 9

This script is functioning properly in Internet Explorer 10 and above, as well as Chrome and other browsers. However, it encounters issues specifically with IE8 and IE9. <table id="table" border="1"> <tbody style="display: table-row-group"&g ...

Incorporating an image within a v-for loop in Vuetify

I am planning to incorporate images at a later stage, but I am currently utilizing v-for and facing a dilemma of how to seamlessly introduce the image within the loop without disrupting its flow. <template> <v-card> <p v-for="item ...

When the button is clicked, bind the value to an object using the specified key in

I'm fairly new to Vue and I'm looking to generate buttons based on my data and show their information when clicked. The 'pets' object contains keys for id and info. (My actual data is more extensive and my code is a bit more complex, bu ...

Executing AngularJS code that returns a promise within an event

In my run function, I am handling the $routeChangeSuccess event. My goal is to use $http to load some data and then change the $template. The issue here is that $http works asynchronously. I have attempted to return a promise inside the event, but it has ...

Is it advisable to implement the modular pattern when creating a Node.js module?

These days, it's quite common to utilize the modular pattern when coding in JavaScript for web development. However, I've noticed that nodejs modules distributed on npm often do not follow this approach. Is there a specific reason why nodejs diff ...

Need inspiration for testing web content with Protractor?

Exploring new possibilities for testing web content with Protractor. Any fresh ideas on what else can be tested? So far, I've checked links to ensure they redirect correctly. I've also verified text color and decoration changes when hovering ove ...

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

Using JQuery's change function with a Button Group is a great way

I encountered an issue where my button group works with the on.click function but not with on.change. <div class="ui buttons"> <button class="ui button">Value 1</button> <button class="ui bu ...

Leverage CSS styling for database values within a PHP framework

How can I style MYSQL database values in HTML using CSS? My vegetarian database row has 'Y' for yes and 'N' for no. I want to apply different styles to these values using CSS as I display them on my PHP-based page. if ($result1->num_ ...

How can I dynamically populate a select menu in HTML without the need to submit any data

Looking for help with an input form in HTML that uses a combination of input and select boxes. My goal is to dynamically populate a select menu based on the data entered into the input boxes. For example: Employee One: Jim Employee Two: John Employee Thre ...

The Facebook SDK fails to activate in Internet Explorer

I am currently working on implementing a Facebook login using the JavaScript SDK. Everything is functioning correctly in most browsers, but I am experiencing issues with certain versions of Internet Explorer. The login functionality is not working on my l ...

How to stop the HTTP Basic Auth popup with AngularJS Interceptors

In the process of developing a web app using AngularJS (1.2.16) with a RESTful API, I encountered an issue where I wanted to send 401 Unauthorized responses for requests with invalid or missing authentication information. Despite having an HTTP interceptor ...

Converting JSON data into an HTML table

I'm struggling to convert a JSON object into an HTML table, but I can't seem to nail the format. DESIRED TABLE FORMAT: Last Year This Year Future Years 45423 36721 873409 CURRENT TABLE FORMAT: Last Year 45423 This ...

Utilize the inherited background color for a linear-gradient effect

Here is the code snippet I am working with: <label className={classes.trigger} htmlFor={uniqueId} ref={labelRef} style={{ background: val, borderColor: val }} /> This is the corresponding CSS: .trigger { display: block; posit ...

Is it necessary to include a request in the API route handler in Next.js when passing parameters?

In my API route handler, I have a function for handling GET requests: import { NextRequest, NextResponse } from "next/server"; export async function GET(req: NextRequest, { params }: { params: { id: string } }) { const { id } = params; try { ...

How to style the second child div when hovering over the first child div using makeStyles in Material UI

I am working on a web project with a parent div and two child divs. I need to apply CSS styles to the second child div when hovering over the first child div. Below is the structure of the render method. <div className={classes.parent}> <div c ...

Transferring Information from Vue to PHP: What You Need to Know

I need assistance with passing data from Vue to PHP. Currently, I receive a JSON object through a PHP query that looks like this: <?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded, ...

Exploring React Native Networking using react-native-router-flux

Hello everyone, I have a quick query. I am looking to assign each Button to a different page. import React, { Component } from 'react'; import { ActivityIndicator, FlatList, Text, View, TouchableOpacity } from 'react-native'; export ...

Tips for inserting a Vue.js variable into a window.open event

Within this snippet of code: <tr v-for="person, index in People" :key='index'> <td> <button type="button" onclick="window.open('/details/'+person.id,'_blank')"> details</butto ...

The issue I'm facing is that the ng-click functionality in Angular JS is not functioning properly when the

Upon loading the page, my JavaScript function creates a tree structure from JSON data and generates a list of anchor tags which look like this: <a ng-click="shareParent(4619)">Some data</a> Despite associating the ng-click directive with the ...