How to create Switch in ReactJS?
Last Updated :
25 Jul, 2024
In this article, we will learn how to create a switch in React that toggles between light and dark mode. We'll use Material-UI's Switch component to achieve this functionality. By the end of this guide, you'll be able to implement a theme switcher that allows users to seamlessly switch between light and dark themes in your application.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
Project Structure:
Project StructureThe updated dependencies in package.json file will look like:
"dependencies": {
"@emotion/react": "^11.13.0",
"@emotion/styled": "^11.13.0",
"@mui/icons-material": "^5.16.4",
"@mui/material": "^5.16.4",
"react": "^18.2.0",
"react-scripts": "5.0.1",
},
Example: Here is an example of how to create a light/dark mode switch using React and Material-UI
JavaScript
import React from 'react';
import { ThemeProvider, createTheme, CssBaseline } from '@mui/material';
import FormControlLabel from '@mui/material/FormControlLabel';
import Switch from '@mui/material/Switch';
const App = () => {
// State to manage the theme mode
const [darkMode, setDarkMode] = React.useState(false);
// Function to handle theme toggle
const handleThemeChange = (event) => {
setDarkMode(event.target.checked);
};
// Create a theme instance
const theme = createTheme({
palette: {
mode: darkMode ? 'dark' : 'light',
},
});
return (
<ThemeProvider theme={theme}>
<CssBaseline /> {/* This component normalizes the CSS across different browsers */}
<div style={{
margin: 'auto',
display: 'block',
width: 'fit-content',
padding: '20px'
}}>
<h3>How to use Switch Component for Light/Dark Mode in ReactJS?</h3>
<FormControlLabel
control={
<Switch
checked={darkMode}
onChange={handleThemeChange}
color="primary"
name="darkMode"
/>
}
label="Switch Dark Mode"
/>
</div>
</ThemeProvider>
);
}
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: