npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@designcise/next-theme-toggle

v4.0.0

Published

A simple theme toggle for Next.js 13+

Downloads

6

Readme

next-theme-toggle

A simple theme toggle for Next.js 13+ that allows switching between light and dark themes. Using this package would result in the following class and style attributes added to the <html> element:

<html class="dark" style="color-scheme:dark">
  <!-- ... -->
</html>

You can then use different CSS selectors to create styles for dark/light themes.

Features

  • Easy implementation with just two lines of code
  • TypeScript Support
  • Types are automatically loaded, whenever applicable
  • No flicker on page load
  • Toggle between light, dark and auto modes
  • Automatically choose color based on prefers-color-scheme when in "auto" mode
  • Update color when prefers-color-scheme changes in auto mode
  • Switch to opposite color when toggling from "auto"
  • Data is stored in localStorage
  • No unnecessary bloat
  • Well-tested

Installation

Prerequisites

  • Next.js 13+
  • React 18+

npm

$ npm install @designcise/next-theme-toggle

yarn

$ yarn add @designcise/next-theme-toggle

Quickstart

NOTE: Please note that this approach relies on using localStorage on the client side to store theme information.

At a bare minimum you need to do the following:

  1. In your Next.js application's root layout file (typically, app/layout.js), do the following:
// app/layout.js
import { ThemeProvider } from '@designcise/next-theme-toggle';
import { themes } from '@designcise/next-theme-toggle/server';

export default async function RootLayout() {
  // 1: wrap components with `ThemeProvider` to pass theme props down to all components
  // 2: optionally pass `storageKey` and `defaultTheme` to `ThemeProvider`
  return (
    <html>
      <body>
        <ThemeProvider storageKey="user-pref" defaultTheme={themes.dark.type}>
          {children}
        </ThemeProvider>
      </body>
    </html>
  )
}

With this setup, the ThemeProvider component will automatically inject an inline script into DOM that takes care of avoiding flicker on initial page load.

NOTE: If you don't specify a storageKey or defaultTheme prop on ThemeProvider, default value will be used for storageKey while absence of defaultTheme would mean that the theme is automatically determined based on prefers-color-scheme.

  1. Create a button to toggle between light and dark theme:
// components/ToggleThemeButton/index.jsx
'use client'

import React, { useContext } from 'react'
import { useTheme } from '@designcise/next-theme-toggle'

export default function ToggleThemeButton() {
  const { toggleTheme } = useTheme()

  return <button onClick={toggleTheme}>Toggle Theme</button>
}

You can also do this manually by using theme, themes, and setTheme(), for example, like so:

// components/ToggleThemeButton/index.jsx
'use client'

import React, { useContext } from 'react'
import { useTheme } from '@designcise/next-theme-toggle'

export default function ToggleThemeButton() {
  const { theme, themes, setTheme } = useTheme()

  return (
    <button onClick={() => setTheme(theme.type === themes.dark.type ? themes.light : themes.dark)}>
      Toggle Theme
    </button>
  )
}
  1. Add toggle button to your page(s):
// app/page.js
import ToggleThemeButton from '@/components/ToggleThemeButton'

export default async function Home() {
  return (
    <main>
      <h1>Hello World</h1>

      <ToggleThemeButton />
    </main>
  )
}
  1. Add styling for dark and light themes:
/* globals.css */
:root body {
  background: white;
}

:root.dark body {
  background: black;
}

or:

/* globals.css */
body {
  background: white;
}

.dark body {
  background: black;
}

or:

/* globals.css */
body {
  background: white;
}

@media (prefers-color-scheme: dark) {
  body {
    background: black;
  }
}

That's it! You should have light/dark theme toggle in your Next.js application.

API

ThemeProvider

You can pass the following props to ThemeProvider:

| Prop | Type | Description | |----------------|:--------------------------------------------:|:---------------------------------------------------------------------------------------:| | children | React.ReactChild|React.ReactChild[] | Components to which the theme is passed down to via context. | | storageKey | String | Name of the key used for storage. Defaults to DEFAULT_STORAGE_KEY in env.helper.ts. | | defaultTheme | String | Default theme ('light', 'dark' or auto) to use on page load. Defaults to auto. |

useTheme()

The useTheme() hook does not take any params; it returns the following:

| Return Value | Type | Description | |---------------|:--------:|:------------------------------------------------------------------------------------------------------------------------------------:| | theme | Object | The active theme (e.g. { type: 'light', color: 'light' }). | | themes | Object | Allowed themes (e.g. { light: { type: 'light', color: 'light' }, dark: ..., auto: ... }). | | setTheme | Function | Setter to set new theme. | | toggleTheme | Function | Toggles the theme between light and dark. When toggling from auto, the opposite color to active color is automatically chosen. |

themes

An object, with the following properties:

| Property | Type | Value | Description | |----------|:------:|:------------------------------------------------:|:-----------------------------------------------------------:| | light | Object | { type: 'light', color: 'light' } | Light theme. | | dark | Object | { type: 'dark', color: 'dark' } | Dark theme. | | auto | Object | { type: 'auto', color: 'dark' &vert; 'light' } | Auto-determine theme color based on prefers-color-scheme. |

NOTE: The themes object can be used in both, client components and server components.

For server components you can import themes like so:

import { themes } from '@designcise/next-theme-toggle/server'

For client components, you can import it like so:

import { themes } from '@designcise/next-theme-toggle'

Testing

Tests are written using React Testing Library and Jest. You can run the tests using the following command:

npm

$ npm test

yarn

$ yarn test

Issues

Reporting

  • File issues at https://github.com/designcise/next-theme-toggle/issues
  • Issue patches to https://github.com/designcise/next-theme-toggle/pulls

Troubleshooting Common Issues

Warning: Extra attributes from the server: class,style in Console

You can safely ignore this warning as it only shows on dev build and not in the production build. This happens because the injected inline script adds additional class and style attributes to the html element which do not originally exist on the server-side generated page, leading to a mismatch in the server-side and client-side rendered page.

Contributing

https://github.com/designcise/next-theme-toggle/blob/main/CONTRIBUTING.md

License

https://github.com/designcise/next-theme-toggle/blob/main/LICENSE.md

Resources