Toggle between useState using Switch from MUI

Issue

trying to build my own Dark Mode for a specific component on my create-react-app site and using MUI. I have the Switch working to change the state on toggle but can’t seem to find how to toggle it back and forth. Basically want to turn page dark on toggle and turn back to light on same toggle button. Suggestions please.

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

Solution

const DarkMode = () => {
    const [color, setColor] = React.useState(false)

    const toggle = () =>{
      setColor(!color);
    }
  return (
    <div style={{ backgroundColor: color ? '#2c2d30' : '#ffffff' }}>
        <Switch onChange={toggle} />
        <h1 style={{ color: color ? '#ffffff' : '#000000' }}>He</h1>
    </div>
  )
}

export default DarkMode

Answered By – David Ho

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.