Dark Mode in React the Easy Way
In recent years, dark mode has surged in popularity across applications and operating systems. It not only reduces eye strain in low-light conditions but also enhances battery life for OLED screens. Implementing dark mode in React apps has never been easier, and in this article, we’ll explore a straightforward method for doing so. Whether you’re a beginner just starting with React or a seasoned developer looking to implement this feature efficiently, this guide is for you.
Understanding Dark Mode and Its Benefits
Dark mode, as the name suggests, is a user interface design that displays light text on a dark background. Here are some key benefits:
- Reduced Eye Strain: Dark themes can reduce glare and make it easier on the eyes, especially in dim environments.
- Battery Saving: On OLED and AMOLED screens, dark pixels use less power, thus extending battery life.
- Enhanced Readability: Many users find content easier to read and comprehend in dark mode.
Preparing Your React Application
Before we implement dark mode, ensure you have a basic React application set up. We will use create-react-app to quickly bootstrap our application. If you haven’t created one yet, you can do so with the following command:
npx create-react-app dark-mode-example
Once your app is ready, navigate to the project directory:
cd dark-mode-example
Setting Up State Management for Dark Mode
We will manage the dark mode state using React’s built-in useState and useEffect hooks. Our application will remember user preferences using local storage.
Creating the Theme Context
First, let’s create a context to share the dark mode state across our components. Create a new file called ThemeContext.js in the src directory:
touch src/ThemeContext.js
Now, add the following code to your ThemeContext.js file:
import React, { createContext, useContext, useState, useEffect } from 'react';
const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [isDarkMode, setIsDarkMode] = useState(() => {
// Get the user's preference from local storage or default to false
return JSON.parse(localStorage.getItem('darkMode')) || false;
});
useEffect(() => {
// Save the user's preference in local storage
localStorage.setItem('darkMode', JSON.stringify(isDarkMode));
document.body.className = isDarkMode ? 'dark' : 'light';
}, [isDarkMode]);
const toggleTheme = () => {
setIsDarkMode((prevMode) => !prevMode);
};
return (
{children}
);
};
export const useTheme = () => useContext(ThemeContext);
Applying the Theme Context in Your Application
Now that we have our theme context set up, let’s integrate it into our main App.js file.
import React from 'react';
import { ThemeProvider } from './ThemeContext';
import TodoApp from './TodoApp'; // assume we will create a TodoApp component for demonstration
const App = () => {
return (
);
}
export default App;
Building a Sample Component to Test Dark Mode
Next, we’ll create a simple component to showcase the dark mode functionality. For this example, we will create a TodoApp component. Create a new file called TodoApp.js in the src directory:
touch src/TodoApp.js
Now, add the following code to your TodoApp.js file:
import React from 'react';
import { useTheme } from './ThemeContext';
const TodoApp = () => {
const { isDarkMode, toggleTheme } = useTheme();
return (
Todo List
{isDarkMode ? 'Dark mode is activated!' : 'Light mode is activated!'}
);
}
export default TodoApp;
Styling the Dark Mode
To make it visually appealing, let’s define some basic CSS for our dark and light themes. Create a CSS file called styles.css in the src directory:
touch src/styles.css
In this CSS file, add the following styles:
body.light {
background-color: #f0f0f0;
color: #333;
}
body.dark {
background-color: #121212;
color: #ffffff;
}
h1 {
font-size: 2em;
}
button {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
background-color: #007bff;
color: #fff;
}
button:hover {
background-color: #0056b3;
}
Now, don’t forget to import this CSS file in your index.js file:
import './styles.css';
Testing Your Dark Mode Implementation
Everything is ready! Now you can start your application using:
npm start
Once the app is running, you should be able to toggle between dark and light mode using the button. The styling will adapt to your chosen mode, effectively showcasing the dark mode functionality.
Extending Functionality with Themes
Now that the basic dark mode is implemented, you might want to extend its functionality by allowing users to select between multiple themes. You can create an array of theme configurations and add a dropdown to select them. This can be done by modifying the context and the TodoApp component to handle the selected theme.
Updating the Theme Context
const themes = {
light: {
body: '#f0f0f0',
text: '#333'
},
dark: {
body: '#121212',
text: '#fff'
}
};
const [theme, setTheme] = useState(themes.light);
useEffect(() => {
document.body.style.backgroundColor = theme.body;
document.body.style.color = theme.text;
}, [theme]);
Making the Changes in TodoApp
Finally, integrate a dropdown in the TodoApp component to change between themes.
setTheme(themes[e.target.value])}>
Light Theme
Dark Theme
Conclusion
Implementing dark mode in a React application can be done efficiently with the use of contexts, hooks, and some straightforward CSS. The approach we’ve discussed is flexible and can be expanded to accommodate more complex requirements. It’s a valuable feature that enhances user experience by allowing customization and comfort. Now go ahead and implement this feature in your projects to add an extra layer of appeal!
For more content like this, be sure to follow our blog or subscribe for updates on the latest tips and tricks in web development!