Creating a Theme Switcher in React
In today’s web development landscape, user experience is paramount. One effective way to enhance UX is by providing a theme switcher that allows users to toggle between light and dark modes. In this article, we’ll explore how to create a simple but efficient theme switcher using React.
Why Use a Theme Switcher?
Dark mode has gained popularity for its aesthetic appeal and potential to reduce eye strain. By giving users control over their viewing preferences, you increase engagement and user satisfaction. Implementing a theme switcher can also be a fun and interactive feature for users, making your application stand out.
Setting Up Your React Project
Let’s get started by setting up a basic React application. If you haven’t created a React app yet, you can do so using Create React App.
npx create-react-app theme-switcher
cd theme-switcher
npm start
This command will set up a basic React application and open it in your default web browser.
Creating the Theme Context
To effectively manage our light and dark themes, we’ll create a context. This will allow any component in our app to access theme-related state and functions.
import React, { createContext, useContext, useState } from 'react';
// Create a context for the theme
const ThemeContext = createContext();
// Create a provider component
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};
return (
{children}
);
};
// Custom hook to use the theme context
export const useTheme = () => {
return useContext(ThemeContext);
};
In this code, we created a ThemeContext along with a ThemeProvider component. The provider holds the current theme state and a method toggleTheme to switch between light and dark modes.
Implementing the Theme Switcher
Next, let’s create a simple button that will allow us to switch themes. We’ll use the custom hook useTheme that we created earlier.
import React from 'react';
import { useTheme } from './ThemeContext';
const ThemeSwitcher = () => {
const { theme, toggleTheme } = useTheme();
return (
);
};
export default ThemeSwitcher;
This component uses the toggleTheme function when the button is clicked. It also updates the button text based on the current theme.
Applying Styles Based on the Theme
Now, we need to apply different styles based on the selected theme. To illustrate this, we’ll create a simple layout with some basic styles.
import React from 'react';
import { ThemeProvider } from './ThemeContext';
import ThemeSwitcher from './ThemeSwitcher';
import './App.css';
const App = () => {
return (
Hello, React!
This is your theme switcher example.
);
};
export default App;
Now let’s create the CSS styles for light and dark themes. You can use CSS variables to switch styles easily.
:root {
--background-color: white;
--text-color: black;
}
.dark {
--background-color: black;
--text-color: white;
}
.App {
background-color: var(--background-color);
color: var(--text-color);
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
button {
padding: 10px 20px;
margin: 20px;
border: none;
cursor: pointer;
}
Now we can dynamically apply the dark class based on the current theme state. Modify the App component to provide this functionality.
const App = () => {
const { theme } = useTheme();
return (
Hello, React!
This is your theme switcher example.
);
};
With these changes, the CSS will adjust according to the chosen theme, creating a visual distinction between light and dark modes.
Persisting the Theme Selection
To improve the user experience further, we can save the user’s theme preference in localStorage. This way, when the user revisits the application, their preferred theme will be applied automatically.
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState(() => {
return localStorage.getItem('theme') || 'light';
});
const toggleTheme = () => {
const newTheme = theme === 'light' ? 'dark' : 'light';
setTheme(newTheme);
localStorage.setItem('theme', newTheme);
};
return (
{children}
);
};
This update checks localStorage for a saved theme preference when the component first renders. It updates the saved theme every time the user switches themes.
Conclusion
In this article, we created a functional theme switcher in React that allows users to toggle between light and dark modes. We implemented the context API to manage theme state, utilized a custom hook for easy accessibility, applied CSS based on the selected theme, and persisted the theme preference in localStorage.
Theme switchers not only enhance user experience but also add a touch of personalization to your application. With just a few lines of code, you can make your app feel more dynamic and user-friendly.
Feel free to extend this example by adding additional themes or customization options. Happy coding!
