React30-Project 16: Implementing Theme Switching in a React Web App

Saurabh Mhatre
5 min readNov 22, 2023
Title image

Introduction:

In this tutorial, we’ll walk through the process of implementing theme switching (Dark theme/Light theme) in a basic web app using React and Bootstrap. We’ll use the useContext hook to manage the theme state, providing a seamless user experience with the ability to switch between different themes.

Explanation of `useContext` Hook for beginners:

Imagine you have a magical bag, and inside that bag, you keep important things that you want to share with all your friends. Now, instead of telling each friend separately about the cool stuff you have in your bag, you use a special horn that magically lets all your friends know at once. The `useContext` hook in React is like that magical horn. It helps different parts of your app talk to each other and share information without having to pass messages around all the time.

Technical Explanation of `useContext` Hook:

In React, when you have information that many components in your app need to know, you might pass that information through a chain of parent and child components. But as your app grows, this can become tedious. The `useContext` hook provides a solution.

It allows you to create a "context," which is like a global storage space. Imagine this context as the magical bag from our previous example. Components that need information from this context can "listen" to it using the `useContext` hook. When the information inside the context changes, all the listening components are automatically updated.

So, it's a way for components to share and access data without passing it through props manually. It makes communication between different parts of your app more straightforward and cleaner.

Prerequisites:

Before starting, ensure you have the following:

  • Node.js installed on your machine
  • Basic knowledge of React.js
  • Code editor (e.g., Visual Studio Code)

Goal:

Implement a theme switching app using `useContext` hook as shown below:

Dark mode
Light mode

Implementation:

Step 1: Set Up a New React App

Set up a new react app using below command:

npx create-react-app theme-switch-app
cd theme-switch-app

Step 2: Install Bootstrap

npm install bootstrap

Step 3: Create Theme Context

Inside the src folder, create a new folder named `context`. Inside it, create a file named `ThemeContext.js`:

// src/context/ThemeContext.js
import React, { createContext, useState } from 'react';

const ThemeContext = createContext();

const ThemeProvider = ({ children }) => {
const [darkTheme, setDarkTheme] = useState(false);

const toggleTheme = () => {
setDarkTheme((prevTheme) => !prevTheme);
};

return (
<ThemeContext.Provider value={{ darkTheme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};

export { ThemeProvider, ThemeContext };

Step 4: Wrap App Component with ThemeProvider

Update src/index.js to wrap the App component with ThemeProvider.

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App";
import { ThemeProvider } from "./context/ThemeContext";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
<StrictMode>
<ThemeProvider>
<App />
</ThemeProvider>
</StrictMode>
);

Step 5: Create ThemeToggle Component

Inside the src folder, create a new folder named `components`. Inside it, create a file named `ThemeToggle.js`:

// src/components/ThemeToggle.js
import React, { useContext } from "react";
import { ThemeContext } from "../context/ThemeContext";

const ThemeToggle = () => {
const { darkTheme, toggleTheme } = useContext(ThemeContext);

return (
<div className="theme-toggle d-flex align-items-center">
<label className="switch">
<input
type="checkbox"
checked={darkTheme}
onChange={toggleTheme}
className="toggle-input"
/>
<span className="slider round"></span>
</label>
<p className="px-2">{darkTheme ? "Dark Theme" : "Light Theme"}</p>
</div>
);
};

export default ThemeToggle;

Step 6: Implement Theme in App Component

Update src/App.js to use Bootstrap and include the ThemeToggle component.

// src/App.js
import React, { useContext } from "react";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import ThemeToggle from "./components/ThemeToggle";
import { ThemeContext } from "./context/ThemeContext";

function App() {
const { darkTheme } = useContext(ThemeContext);

return (
<div className={`App ${darkTheme ? "dark-theme" : "light-theme"}`}>
<header className="App-header">
<h1>Theme Switching App</h1>
<ThemeToggle />
</header>
<div className="body">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sagittis
ut orci nec sodales. Donec dignissim tortor eget metus mollis, vel
gravida lectus accumsan. Vestibulum dapibus tortor in massa lacinia
tempus. Morbi et dolor et ipsum eleifend viverra in a erat. Nam vel
rhoncus urna, eu finibus justo. Nunc sodales lacinia turpis, vitae
viverra erat rutrum eget. Phasellus dapibus imperdiet odio, consectetur
rutrum velit pharetra elementum. Aliquam tempor mauris nec consequat
cursus. Nullam mi libero, sodales ut ornare at, lobortis ut metus. Cras
quis ex non odio vehicula elementum et in magna. Phasellus eget
ullamcorper orci. Duis in massa accumsan, vehicula arcu sit amet,
pulvinar mi. Cras massa lorem, facilisis a arcu eu, mollis convallis
urna. Aliquam semper tristique nunc vel placerat. Etiam nec magna ex{" "}
</div>
</div>
);
}

export default App;

Step 7: Add Styling

Update src/App.css to include styling for dark and light themes.

/* src/App.css */
.dark-theme {
background-color: #333;
color: #fff;
}

.light-theme {
background-color: #fff;
color: #333;
}

/* Add other styles as needed */

Step 8: Run the App

Run below command in terminal to run the app:

npm start

Visit http://localhost:3000 in your browser to see the theme-switching app.

Source code:-

Codesandbox

Conclusion:

Congratulations! In this tutorial, we successfully implemented theme switching in a React web app using Bootstrap and the useContext hook. Users can now toggle between Dark and Light themes seamlessly. This example demonstrates the power of React context and hooks for managing global state in a React application. Feel free to extend this example by adding more components and styles based on your project requirements.

Check out my YouTube channel for more content below:

SaurabhNative — YouTube

And next part in the series to learn how to integrate React Query into a basic web app:

React30-Project17

--

--