COGBlog
Cat Woman
Nov 05, 2021

How to create Dark Mode in ReactJS using Material UI ?

Example: After creating a basic to react app, we will make changes in App. js as follows :

Step 1: Import ThemeProvider and createMuiTheme

import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';

Step 2: Set up the toggle logic in App.js

const [toggleDark, settoggleDark] = useState(false); const myTheme=createMuiTheme({ // Theme settings palette:{ type: toggleDark ? 'dark' : 'light', } });

Step 3: Here I am creating a new SmallComponent which will be our new component imported in App. j (You can customize it to your own component. Here I am focusing on implementing dark mode in already existing code). Pass the states for dark mode (toggle dark and settoggleDark), which will be used to switch between light and dark mode. Wrap up your component inside the ThemeProvider and pass your customized theme.

<ThemeProvider theme={myTheme}> <SmallComponent toggleDark={toggleDark} settoggleDark={settoggleDark}/> </ThemeProvider>

Step 4: Trigger toggle using onChange Switch in SmallComponent.js

const handleModeChange = () => { settoggleDark(!toggleDark) };<Switch checked={toggleDark} onChange={handleModeChange} name="toggleDark" color="default" />

Cat Woman

Cat Woman

A Gotham City burglar who typically wears a tight, one-piece outfit and uses a bullwhip for a weapon.

Leave a Reply

Related Posts

Topics

Developed with ❤️‍🔥 EdisonAbdiel™