Security News
JavaScript Leaders Demand Oracle Release the JavaScript Trademark
In an open letter, JavaScript community leaders urge Oracle to give up the JavaScript trademark, arguing that it has been effectively abandoned through nonuse.
nextjs-themes
Advanced tools
Unleash the Power of React Server Components! Use multiple themes on your site with confidence, without losing any advantages of React Server Components.
This is a sister package of react18-themes. Initially we targeted only Next.js and thus this package was named
nextjs-themes
. However, we have expanded support forVite
andRemix
as well. And thus published a package with more generic name,react18-themes
.
We recommend using react18-themes for Remix. This package is maintained with specific focus on Next.js and Vite. Most of the functionality of this package along with extended support for other build tools is available in react18-themes
🤟 👉 Unleash the Power of React Server Components
This project was originally inspired by next-themes. Next-themes is an awesome package, however, it requires wrapping everything in a provider. The provider has to be a client component as it uses hooks. And thus, it takes away all the benefits of Server Components.
nextjs-themes
removes this limitation and enables you to unleash the full power of React 18 Server Components. In addition, it adds more features and control over how you theme your app. Stay tuned!
import from nextjs-themes/client/component
)appDir
useTheme
hooklocalStorage
or sessionStorage
(to avoid persistance)Check out the live example.
$ pnpm add nextjs-themes
OR
$ npm install nextjs-themes
OR
$ yarn add nextjs-themes
$ pnpm add nextjs-themes-lite
or
$ npm install nextjs-themes-lite
or
$ yarn add nextjs-themes-lite
You need Zustand as a peer-dependency
The best way is to add a Custom App
to use by modifying _app
as follows:
Adding dark mode support takes 2 lines of code:
import { ThemeSwitcher } from "nextjs-themes";
function MyApp({ Component, pageProps }) {
return (
<>
<ThemeSwitcher forcedTheme={Component.theme} />
<Component {...pageProps} />
</>
);
}
export default MyApp;
⚡🎉Boom! Just a couple of lines and your dark mode is ready!
Check out examples for advanced usage.
app
router (Server Components)If your app is mostly serving static content, you do not want the overhead of SSR. Use
NextJsSSGThemeSwitcher
in this case. When using this approach, you need to use CSS general sibling Combinator (~) to make sure your themed CSS is properly applied. See (HTML & CSS)[#html--css].
Update your app/layout.jsx
to add ThemeSwitcher
from nextjs-themes
, and NextJsSSGThemeSwitcher
from nextjs-themes/server
. NextJsSSGThemeSwitcher
is required to avoid flash of un-themed content on reload.
// app/layout.jsx
import { ThemeSwitcher } from "nextjs-themes";
import { NextJsSSGThemeSwitcher } from "nextjs-themes/server/nextjs";
export default function Layout({ children }) {
return (
<html lang="en">
<head />
<body>
/** use NextJsSSGThemeSwitcher as first element inside body */
<NextJsSSGThemeSwitcher />
<ThemeSwitcher />
{children}
</body>
</html>
);
}
Woohoo! You just added multiple theme modes and you can also use Server Component! Isn't that awesome!
If your app is serving dynamic content and you want to utilize SSR, continue using
ServerSideWrapper
component to replacehtml
tag inlayout.tsx
file.
Update your app/layout.jsx
to add ThemeSwitcher
and ServerSideWrapper
from nextjs-themes
. ServerSideWrapper
is required to avoid flash of un-themed content on reload.
// app/layout.jsx
import { ThemeSwitcher } from "nextjs-themes";
import { ServerSideWrapper } from "nextjs-themes/server/nextjs";
export default function Layout({ children }) {
return (
<ServerSideWrapper tag="html" lang="en">
<head />
<body>
<ThemeSwitcher />
{children}
</body>
</ServerSideWrapper>
);
}
Woohoo! You just added dark mode and you can also use Server Component! Isn't that awesome!
That's it, your Next.js app fully supports dark mode, including System preference with prefers-color-scheme
. The theme is also immediately synced between tabs. By default, nextjs-themes modifies the data-theme
attribute on the html
element, which you can easily use to style your app:
:root {
/* Your default theme */
--background: white;
--foreground: black;
}
[data-theme="dark"] {
--background: black;
--foreground: white;
}
// v2 onwards when using NextJsSSGThemeSwitcher, we need to use CSS Combinators
[data-theme="dark"] ~ * {
--background: black;
--foreground: white;
}
You can also show different images based on the current theme.
import Image from "next/image";
import { useTheme } from "nextjs-themes";
function ThemedImage() {
const { resolvedTheme } = useTheme();
let src;
switch (resolvedTheme) {
case "light":
src = "/light.png";
break;
case "dark":
src = "/dark.png";
break;
default:
src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
break;
}
return <Image src={src} width={400} height={400} />;
}
export default ThemedImage;
In case your components need to know the current theme and be able to change it. The useTheme
hook provides theme information:
import { useTheme } from "nextjs-themes";
const ThemeChanger = () => {
/* you can also improve performance by using selectors
* const [theme, setTheme] = useTheme(state => [state.theme, state.setTheme]);
*/
const { theme, setTheme } = useTheme();
return (
<div>
The current theme is: {theme}
<button onClick={() => setTheme("light")}>Light Mode</button>
<button onClick={() => setTheme("dark")}>Dark Mode</button>
</div>
);
};
import { ForceTheme } from "nextjs-themes";
function MyPage() {
return (
<>
<ForceTheme theme={"my-theme"} />
...
</>
);
}
export default MyPage;
For pages router, you have 2 options. One is the same as the app router and the other option which is compatible with next-themes
is to add theme
to your page component as follows.
function MyPage() {
return <>...</>;
}
MyPage.theme = "my-theme";
export default MyPage;
In a similar way, you can also force color scheme.
Forcing color scheme will apply your defaultDark or defaultLight theme, configurable via hooks.
Next Themes is completely CSS independent, it will work with any library. For example, with Styled Components you just need to createGlobalStyle
in your custom App:
// pages/_app.js
import { createGlobalStyle } from "styled-components";
import { ThemeSwitcher } from "nextjs-themes";
// Your themeing variables
const GlobalStyle = createGlobalStyle`
:root {
--fg: #000;
--bg: #fff;
}
[data-theme="dark"] {
--fg: #fff;
--bg: #000;
}
`;
function MyApp({ Component, pageProps }) {
return (
<>
<GlobalStyle />
<ThemeSwitcher forcedTheme={Component.theme} />
<Component {...pageProps} />
</>
);
}
In your tailwind.config.js
, set the dark mode property to class:
// tailwind.config.js
module.exports = {
darkMode: "class",
};
⚡🎉Boom! You are ready to use darkTheme in tailwind.
Caution! Your class must be set to
"dark"
, which is the default value we have used for this library. Tailwind, as of now, requires that class name must be"dark"
for dark-theme.
That's it! Now you can use dark-mode specific classes:
<h1 className="text-black dark:text-white">
6f17cce: # Additonal CSS Combinations + Ensure seamless support for Tailwind
[data-theme=]
selectors work as before.ServerSideWrapper
or NextJsServerTarget
or NextJsSSGThemeSwitcher
, you need to convert forcedPages
elements to objects of the shape { pathMatcher: RegExp | string; props: ThemeSwitcherProps }
.resolvedColorScheme
for more sturdy dark/light/system modes[data-th=""]
and [data-color-scheme=""]
for dark/light varients of themes[data-csp=""]
to style based on colorSchemePreference.themeTransition
prop to ThemeSwitcher
component to apply smooth transition while changing theme.setThemeSet
to set lightTheme
and darkTheme
together.For server side syncing, we need to use cookies and headers. This means that this component and its children can not be static. They will be rendered server side for each request. Thus, we are avoiding the wrapper. Now, only the NextJsSSGThemeSwitcher
will be rendered server side for each request and rest of your app can be server statically.
Take care of the following while migrating to v2
.
Next.js
app router or server components other than updating cookies policy if needed.cookies
in place of localStorage
. (You might want to update cookies policy accordingly.)NextJsSSGThemeSwitcher
in addition to ServerSideWrapper
for Next.js
. You no longer need to use a wrapper component which broke static generation and forced SSR.app
router (Server Components)defaultDarkTheme
is renamed to darkTheme
setDefaultDarkTheme
is renamed to setDarkTheme
defaultLightTheme
is renamed to lightTheme
setDefaultLightTheme
is renamed to setLightTheme
Want handson course for getting started with Turborepo? Check out React and Next.js with TypeScript
Do I need to use CSS variables with this library?
Nope. It's just a convenient way. You can hard code values for every class as follows.
.my-class {
color: #555;
}
[data-theme="dark"] .my-class {
color: white;
}
Why is resolvedTheme
and resolvedColorScheme
necessary?
When supporting the System theme preference, and forced theme/colorScheme pages, you want to make sure that's reflected in your UI. This means your buttons, selects, dropdowns, or whatever you use to indicate the current colorScheme should say "system" when the System colorScheme preference is active. And also the appropreate theme is available in resolvedTheme.
resolvedTheme
is then useful for modifying behavior or styles at runtime:
const { resolvedTheme, resolvedColorScheme } = useTheme();
const background = getBackground(resolvedTheme);
<div style={{ color: resolvedColorScheme === 'dark' ? white : black, background }}>
If we didn't have resolvedTheme
and only used theme
, you'd lose information about the state of your UI (you would only know the theme is "system", and not what it resolved to).
Licensed as MIT open source.
Note: This package uses cookies to sync theme with server components
with 💖 by Mayank Kumar Chaudhari
FAQs
Unleash the Power of React Server Components! Use multiple themes on your site with confidence, without losing any advantages of React Server Components.
The npm package nextjs-themes receives a total of 885 weekly downloads. As such, nextjs-themes popularity was classified as not popular.
We found that nextjs-themes demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
In an open letter, JavaScript community leaders urge Oracle to give up the JavaScript trademark, arguing that it has been effectively abandoned through nonuse.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.