Hello developers! Welcome to this article, where we'll show you how to add dark and light themes to your project using ReactJS.
In the modern world of the internet, how users feel while using a website or app is most important. If we are giving them options, such as choosing between dark and light themes, it can help improve their experience. Adding these options to the website can make users happier and make it easier for everyone to use.
In this easy-to-follow guide, we'll show you step-by-step how to add dark and light themes to your ReactJS website using Material-UI.
Prerequisites
Before diving into the implementation, ensure you have the following:
- Basic knowledge of ReactJS.
- Familiarity with the Material-UI library.
- Node.js is installed on your system.
Integrating Dark and Light Themes
- Step 1: Setting Up the Project
- Step 2: Installing Dependencies
- Step 3: Creating Components
- Step 4: Implementing Dark and Light Themes
- Step 5: Test Your Code
Step 1: Setting Up the Project
npx create-react-app dark-light-theme-react
Step 2: Installing Dependencies
Next, install Material-UI and its related dependencies using npm or yarn.
// For npm
npm i @mui/material @emotion/react @emotion/styled @mui/icons-material
// For yarn
yarn add @mui/material @emotion/react @emotion/styled @mui/icons-material
Step 3: Creating Components
Navigate to the 'src' directory and create a 'components' folder. Within this folder, create three files: 'Navbar.jsx', 'MyComponent.jsx', and 'Footer.jsx'.
Navbar.jsx:
A navigation bar component to toggle between dark and light themes.
// src/components/Navbar.jsx
import React from "react";
import { AppBar, Toolbar, IconButton } from "@mui/material";
import Brightness4Icon from '@mui/icons-material/Brightness4';
import Brightness7Icon from '@mui/icons-material/Brightness7';
const NavBar = ({ toggleDarkTheme, toggleDarkMode }) => {
return (
<AppBar position="static" color="primary">
<Toolbar style={{ display: 'flex', justifyContent: 'space-between' }}>
<h1>Theme Changer</h1>
<div style={{ display: 'flex', alignItems: 'center' }}>
<ul style={{ display: "flex", gap: '50px', listStyle: 'none', paddingRight: '20px' }}>
<li>Home</li>
<li>About</li>
<li>Project</li>
<li>Contact</li>
</ul>
<IconButton onClick={toggleDarkTheme} color="inherit">
{toggleDarkMode ? <Brightness7Icon /> : <Brightness4Icon />}
</IconButton>
</div>
</Toolbar>
</AppBar >
);
};
export default NavBar;
This code imports the necessary items and icons from Material-UI to create a NavBar component. The component switches between dark and light themes when users interact with the IconButton. The icon's color stays white because it's set to inherit. Also, we use a ternary operator to decide which icon to show based on the toggleDarkMode state.
MyComponent.jsx:
The user interface design elements are included in this component.
// src/components/MyComponent.jsx
import React from "react";
import { Card, CardMedia } from "@mui/material";
const MyComponent = () => {
return (
<div style={{ display: 'flex' }}>
{/* Left Side */}
<Card style={{ flex: 1, marginLeft: 10, display: 'grid', placeItems: 'center' }}>
<div style={{ margin: '10px', }}>
<h1>Welcome to our site</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dignissimos corrupti dolore et quibusdam distinctio quaerat dolor laboriosam, ratione saepe nihil dolorem mollitia sapiente recusandae assumenda obcaecati ut voluptas ab praesentium.</p>
</div>
</Card>
{/* Right Side */}
<Card style={{ flex: 1, marginRight: 10 }}>
<CardMedia
component="img"
image="https://images.pexels.com/photos/546819/pexels-photo-546819.jpeg"
alt="Semaphore"
/>
</Card>
</div>
);
};
export default MyComponent;
In this code, we have created a component of React named MyComponent. It uses Material-UI's Card and CardMedia components to show content and an image. The component shows a title and text on the left and an image on the right using a flexbox layout.
Footer.jsx:
// src/components/Footer.jsx
import React from "react";
import { Box } from "@mui/material";
const Footer = () => {
return (
<Box sx={{
position: 'fixed',
bottom: 0,
width: '100%',
display: "flex",
justifyContent: 'center',
padding: '20px',
}}>
Where creativity meets functionality – welcome to our project!😊
</Box >
);
};
export default Footer;
This code makes a React Footer using Material-UI's Box. It shows a footer at the bottom of the page with a message.
Step 4: Implementing Dark and Light Themes
In your App.js, import the necessary components and set up the theme toggle functionality using React's state management.
// App.js
import React, { useState } from "react";
import { ThemeProvider, createTheme } from "@mui/material/styles";
import CssBaseline from "@mui/material/CssBaseline";
import NavBar from "./components/Navbar";
import MyComponent from "./components/MyComponent";
import Footer from "./components/Footer";
import { Container } from "@mui/material";
export default function App() {
const [toggleDarkMode, setToggleDarkMode] = useState(false);
const toggleDarkTheme = () => {
setToggleDarkMode(!toggleDarkMode);
};
const darkTheme = createTheme({
palette: {
mode: toggleDarkMode ? 'dark' : 'light',
primary: {
main: '#009bf5',
},
},
});
return (
<ThemeProvider theme={darkTheme}>
<CssBaseline />
<NavBar toggleDarkTheme={toggleDarkTheme} toggleDarkMode={toggleDarkMode} />
<Container maxWidth="md" sx={{ marginTop: 4 }}>
</Container>
<MyComponent />
<Footer />
</ThemeProvider>
);
}
In the App.js file, we start by using the useState hook to manage the toggleDarkMode state, determining whether the application should display a dark or light theme.
The toggleDarkTheme function then enables smooth switching between these themes, updating the toggleDarkMode state accordingly.
Next, we define a darkTheme object using Material-UI's createTheme function. This object configures the color palette, sets the primary color (you can set anything), and adjusts the theme mode based on the toggleDarkMode state.
To keep the theme consistent across the app, we enclose it in the ThemeProvider component. This makes sure all components get the chosen theme throughout the hierarchy.
To ensure a uniform appearance across different browsers, we include the CSSBaseline component.
In the end, key components such as the NavBar, MyComponent, and Footer are displayed inside the ThemeProvider. This lets them change their look automatically depending on the chosen theme.
Step 5: Test your code
Test your code by running it with npm start to view your UI in the browser and ensure everything works smoothly.
Great! In this project, we didn't concentrate on making it responsive because our main goal was to understand its functionality thoroughly.
Conclusion
Dark mode is not only popular, but it is also a great option that allows users to navigate our website easily, especially at night time. With this, users can easily read the content of our website without straining their eyes. The biggest advantage of this is that, with the help of this future, the batteries of phones and computers will also be saved. This is why people like it so much. It is very important for today's modern interface so that the user can do anything with concentration.
If you have any questions about this article or related to web development, you can ask them in the question box below, and you will get a reply as soon as possible.