Create Mui Dark Mode switch using React Context

How to creaye dark theme switch in using Material UI switch and React Context and State Hooks


Material UI or MUI is one word for all UI needs. It is well documented and easy to use. I really enjoyed it.

In this post I would like to demonstrate how to create dark-mode switcher using the React Context and Material UI switch component.

Context

We already covered the dynamic-Context in detail, please use the posts to learn more about Context and the basic step required.

Our context setup with look like the following

//context/themeContext.js
 import React from 'react';

export const ThemeContext = React.createContext({
    theme: 'dark',
    setTheme: () => { }
  })
  
//app.js or _app.js
 
import React, { useState } from 'react'; 
import { ThemeContext } from '../context/themeContext';


function MyApp({ Component, pageProps }) {
  const [theme, setTheme] = useState("light")
  const value = { theme, setTheme };
 

  return (
  
      <ThemeContext.Provider value={value}   >
        <Component {...pageProps} />
      </ThemeContext.Provider>
    
  );
}

Theme Switcher

A MUI customized switch can be used to create a theme switcher. We also need to access the context using the useContext hook. The code will look like the following.

The complete switch snippet can be obtained from Material UI switch documentation page.

import * as React from 'react';
import clsx from 'clsx';
import { styled } from '@mui/system';
import { useSwitch } from '@mui/core/SwitchUnstyled';
import { Tooltip } from '@mui/material';
import { ThemeContext } from '../context/themeContext';
 ...
function MUISwitch(props) {
  const { theme, setTheme } = React.useContext(ThemeContext)
  const { getInputProps, checked, disabled, focusVisible } = useSwitch(props);
  const stateClasses = {
    checked,
    disabled,
    focusVisible,
  };
  var mode = {

  };

 
  React.useEffect(() => {
    const mode = stateClasses.checked ? 'dark' : 'light'
    setTheme(mode)
  }, [stateClasses])
  return (
    <Tooltip title="Theme switcher">
      <SwitchRoot className={clsx(stateClasses)} >
        <SwitchTrack>
          <SwitchThumb className={clsx(stateClasses)} />
        </SwitchTrack>
        <SwitchInput {...getInputProps()} aria-label="Demo switch" />
      </SwitchRoot>
    </Tooltip>

  );
}

export default function UseSwitchesCustom() {
  return <MUISwitch defaultChecked />;
}

The switcher component can be placed anywhere in component tree and it can change the context value, due to dynamic context.

Tracking changes

In order observe changes in state of the switch component , we can use useEffect and the stateClass. Note that there is no event handler attached to the component.

Implement the Theme

The theme can be implemented as you wish, one of the suggested way is to create a component to implement the theme and wrap other components inside it. Such a component can be .

mport React from 'react'
import { createTheme, ThemeProvider, styled } from '@mui/material/styles';
import { ThemeContext } from '../context/themeContext';

export default function BaseTheme(props) {
    const { theme, setTheme } = React.useContext(ThemeContext)
    const theme1 = createTheme(
        {
            palette:
                { mode: theme }
        }
    );

    console.log('Current Theme - ' + JSON.stringify(theme));
    return (
        <div>
            <ThemeProvider theme={theme1} >
                {props.children}
            </ThemeProvider>
        </div>
    )
}

That’s it.

Leave comment and questions

Dynamic context in React

How to make a React context update dynamically on functional component tree.


Dynamic context is programing concept it is not a React feature. Dynamic context allow us update the state from deep nested components. Let’s dive into the example

We are going to use the following

  • useState
  • useContext
  • React.createContext

State

What is a state in React? State is where we kept our data, it can be simple any value, such as count, an User object, or an array of Posts etc.

Context

Context is simplest way to pass state through component tree in Reactjs. It requires a context and a state. A context provider allow us to initialize/update the state. In our example we use provider for initialization only, rest of the work is done with setter function.

Language example

A language example is the simplest way to demonstrate the use of Context and hooks in React. In the App.js create the LanguageContext and inititalContext

This is functional component example in which a Language context used to store and manipulate state.

Create Context

//App.js
const LanguageContext = React.createContext({
  language: "en",
  setLanguage: () => {}
});

Notice the setLanguage key, it is function placeholder for updating the state, and all component using the context get the new value. React Context also provides Provider to update the state.

The language state is initialized with en value, short for English.