Implementing a dynamic theme switcher in Next.js involves a few steps. Here's a simplified guide to get you started:
jsx// themes/ThemeContext.js
import { createContext, useState, useContext } from 'react';
const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
export const useTheme = () => useContext(ThemeContext);
ThemeProvider
to provide access to the theme context throughout the app.jsx// pages/_app.js
import { ThemeProvider } from '../themes/ThemeContext';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return (
<ThemeProvider>
<Component {...pageProps} />
</ThemeProvider>
);
}
export default MyApp;
css/* styles/themes/light.css */
body {
background-color: #fff;
color: #000;
}
/* styles/themes/dark.css */
body {
background-color: #222;
color: #fff;
}
jsx// components/ThemeToggle.js
import { useTheme } from '../themes/ThemeContext';
const ThemeToggle = () => {
const { theme, toggleTheme } = useTheme();
return (
<button onClick={toggleTheme}>
Switch to {theme === 'light' ? 'Dark' : 'Light'} Theme
</button>
);
};
export default ThemeToggle;
jsx// pages/index.js
import { useTheme } from '../themes/ThemeContext';
import ThemeToggle from '../components/ThemeToggle';
import styles from '../styles/Home.module.css';
export default function Home() {
const { theme } = useTheme();
return (
<div className={styles.container}>
<ThemeToggle />
<main className={styles.main}>
<h1 className={styles.title}>Welcome to Next.js!</h1>
</main>
</div>
);
}
jsx// pages/_app.js
import { useEffect } from 'react';
import { useTheme } from '../themes/ThemeContext';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
const { theme } = useTheme();
useEffect(() => {
if (theme === 'light') {
import('../styles/themes/light.css').then();
} else {
import('../styles/themes/dark.css').then();
}
}, [theme]);
return <Component {...pageProps} />;
}
export default MyApp;
With these steps, you should have a basic dynamic theme switcher implemented in your Next.js app. You can expand upon this foundation by adding more themes or customizing the implementation to suit your needs.