To implement a dark mode switch with Next.js and a theme provider, you can use a combination of libraries like styled-components
for styling and next-themes
for handling the theme switching. Here's a step-by-step guide:
Install Dependencies:
Make sure you have the required dependencies installed:
bashnpm install next-themes styled-components
Create a ThemeProvider:
Create a ThemeProvider
component using styled-components
to manage the theme state.
jsx// components/ThemeProvider.js
import { ThemeProvider as StyledThemeProvider } from 'styled-components';
const themes = {
light: {
background: '#ffffff',
text: '#000000',
},
dark: {
background: '#121212',
text: '#ffffff',
},
};
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = React.useState('light');
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
<StyledThemeProvider theme={themes[theme]}>
{children({ theme, toggleTheme })}
</StyledThemeProvider>
);
};
export default ThemeProvider;
Create a Layout Component:
Create a layout component that uses the ThemeProvider
and useTheme
from styled-components
to apply styles based on the theme.
jsx// components/Layout.js
import { useTheme } from 'styled-components';
import ThemeProvider from './ThemeProvider';
const Layout = ({ children }) => {
const theme = useTheme();
return (
<div style={{ background: theme.background, color: theme.text }}>
{children}
</div>
);
};
export default Layout;
Integrate with Next.js:
Integrate the next-themes
library into your Next.js app by wrapping the ThemeProvider
around the App
component in the pages/_app.js
file.
jsx// pages/_app.js
import { ThemeProvider } from 'next-themes';
import Layout from '../components/Layout';
function MyApp({ Component, pageProps }) {
return (
<ThemeProvider defaultTheme="light" attribute="class" enableSystem>
{({ theme, toggleTheme }) => (
<Layout>
<Component {...pageProps} />
<button onClick={toggleTheme}>
Toggle {theme === 'light' ? 'Dark' : 'Light'} Mode
</button>
</Layout>
)}
</ThemeProvider>
);
}
export default MyApp;
Note that in this example, the enableSystem
prop is used to allow the theme to be automatically set based on the user's system preferences.
Now, you should be able to toggle between dark and light modes using the provided button. The theme provider will handle the styling based on the current theme. Customize the styles and themes in the ThemeProvider
and Layout
components as needed for your application.