To implement dark mode in a React app, you can follow these steps:
import React, { createContext, useState, useContext } from 'react';
const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [isDarkMode, setIsDarkMode] = useState(false);
const toggleDarkMode = () => {
setIsDarkMode(prevMode => !prevMode);
};
return (
<ThemeContext.Provider value={{ isDarkMode, toggleDarkMode }}>
{children}
</ThemeContext.Provider>
);
};
export const useTheme = () => useContext(ThemeContext);
ThemeProvider
component in your main App.js
file:import React from 'react';
import { ThemeProvider } from './ThemeContext';
import Home from './Home';
const App = () => {
return (
<ThemeProvider>
<Home />
</ThemeProvider>
);
};
export default App;
useTheme
hook in your components to access the theme state and toggle function:import React from 'react';
import { useTheme } from './ThemeContext';
const Home = () => {
const { isDarkMode, toggleDarkMode } = useTheme();
return (
<div className={isDarkMode ? 'dark-mode' : ''}>
<h1>Welcome to my dark mode app!</h1>
<button onClick={toggleDarkMode}>Toggle Dark Mode</button>
</div>
);
};
export default Home;
index.css
or a separate CSS file:body.dark-mode {
background-color: #333;
color: #fff;
}
Now, you have successfully implemented dark mode in your React app using a context provider and hook.