Coder Social home page Coder Social logo

xeoneux / next-dark-mode Goto Github PK

View Code? Open in Web Editor NEW
217.0 3.0 8.0 1.77 MB

๐ŸŒ‘ Enable dark mode for Next.js apps

Home Page: https://next-dark-mode.vercel.app

License: MIT License

TypeScript 80.69% CSS 19.31%
next nextjs react reactjs dark-mode theme dark-theme night-mode night-theme prefers-color-scheme

next-dark-mode's Introduction

next-dark-mode

๐ŸŒ“ Theme your Next.js apps with a Dark Mode

license npm bundle size npm version

Contents:

Features

Auto mode

next-dark-mode optionally supports auto mode which automatically switches the user's theme as per the color mode selected on their operating system.

Windows and macOS both support setting the dark or light mode based on the time of the day.

It is achieved via prefers-color-scheme media query.

No page load glitch

next-dark-mode uses configurable cookies to persist the state of the current theme, one for the auto mode and the other for the dark mode.

This prevents the common page load glitch with the local storage approach where the app loads on the client and then the state of the user's theme is fetched.

You can see it in this implementation by Pantaley Stoyanov.

NOTE: This library is not compatible with Next.js 9's Auto Partial Static Export feature as it has to read the cookies in getInitialProps function, which makes all pages incompatible with Automatic Partial Static Export feature.

Requirements

To use next-dark-mode, you must use [email protected] or greater which includes Hooks.

Installation

$ yarn add next-dark-mode

or

$ npm install next-dark-mode

Usage

  1. Wrap your _app.js component (located in /pages) with the HOC withDarkMode

    // _app.js
    import App from 'next/app'
    import withDarkMode from 'next-dark-mode'
    
    export default withDarkMode(App)
  2. You can now use the useDarkMode hook anywhere in your app

    import { useDarkMode } from 'next-dark-mode'
    
    const MyComponent = props => {
      const {
        autoModeActive,    // boolean - whether the auto mode is active or not
        autoModeSupported, // boolean - whether the auto mode is supported on this browser
        darkModeActive,    // boolean - whether the dark mode is active or not
        switchToAutoMode,  // function - toggles the auto mode on
        switchToDarkMode,  // function - toggles the dark mode on
        switchToLightMode, // function - toggles the light mode on
      } = useDarkMode()
    
     ...
    }

With CSS-in-JS libraries (like emotion or styled-components)

  1. Wrap your _app.js component (located in /pages) with the HOC withDarkMode and pass the values to the ThemeProvider so that you can use it in your components

    // _app.js
    import { ThemeProvider } from '@emotion/react' // or styled-components
    import withDarkMode from 'next-dark-mode'
    
    function MyApp({ Component, darkMode, pageProps }) {
      const { autoModeActive, autoModeSupported, darkModeActive } = darkMode
    
      return (
        <ThemeProvider theme={{ darkMode: darkModeActive, ...(other values) }}>
          <Component {...pageProps} />
        </ThemeProvider>
      )
    }
    
    export default withDarkMode(MyApp)

Configuration

The withDarkMode function accepts a config object as its second argument. Every key is optional with default values mentioned:

  • autoModeCookieName: string - Name of the cookie used to determine whether the auto preset is enabled. Defaults to 'autoMode'.
  • cookieOptions: object - Configuration options for the cookies that gets set on the client. Defaults to { sameSite: 'lax' }.
  • darkModeCookieName: string - Name of the cookie used to determine whether the dark preset is enabled. Defaults to 'darkMode'.
  • defaultMode: string - Determines the default color mode when there's no cookie set on the client. This usually happens on the first ever page load. It can either be 'dark' or 'light' and it defaults to 'light'.

Resources

next-dark-mode's People

Contributors

xeoneux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

next-dark-mode's Issues

Cannot use the hook with styled-components

disclaimer: I'm new to next.

  const {
    autoModeActive,
    autoModeSupported,
    darkModeActive,
    switchToAutoMode,
    switchToDarkMode,
    switchToLightMode,
  } = darkMode

this works well in_app, but when I try to use this as hook in a component, I can't use the following functions:

const {
    switchToAutoMode,  // function - toggles the auto mode on
    switchToDarkMode,  // function - toggles the dark mode on
    switchToLightMode, // function - toggles the light mode on
  } = useDarkMode()
  console.log(useDarkMode())

Sample Project?

Awesome project. Do you have a working next.js sample project that can be referred to as an example?

Not setting cookie error

Hi @xeoneux!
I'm using next-dark-mode with nextjs + material UI. I'm getting those errors from the server:

Not setting "autoMode" cookie. Response has finished.
You should set cookie before res.send()
Not setting "darkMode" cookie. Response has finished.
You should set cookie before res.send()

Implementation:

Screenshot 2021-06-25 at 15 13 43

Any idea about how I could solve that?

SSG support

The library is awesome!
Is there any plans of supporting getStaticProps as using the HOC with _app.js opts-out automatic static optimisation?
Thank you.

Together with `@sentry/nextjs` this will break production builds

See getsentry/sentry-javascript#5906

Sentry expects the getInitialProps function to return { pageProps: unknown} to set something on pageProps.
Currently this HOC, will return {initialProps: {pageProps: unknown }, ...}.
Which will cause Sentry to run into an runtime type error.

Our current workaround is:

// _app.ts

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

MyApp.getInitialProps = async (appContext: AppContext) =>
	App.getInitialProps(appContext)

const WithDarkApp = withDarkMode(MyApp)
const oldInitialProps = WithDarkApp.getInitialProps

// This fixes, that sentry expects there to be no extra `initialProps` field, and instead directly expects the `pageProps` field
WithDarkApp.getInitialProps = async (appContext: AppContext) => {
	const initialProps = await oldInitialProps(appContext)
	return {
		...initialProps?.initialProps,
		...initialProps,
	}
}

export default WithDarkApp

I think ideally this should be fixed in the library directly, but it could theoretically break some apps, if they rely on this current behavior.

If desired, I might be able to come up with a fix myself (if my time permits ๐Ÿ˜“), but wanted to gauge feedback first.

Automatic static optimization automatic opt-out problem.

Thanks for the great library.

Using next-dark-mode causes Next.js app to render pages server-side, thus significantly slowing down first content render by implementing getInitialProps. Is there a way to avoid it?

Here's the build output:

$ next build
info  - Loaded env from D:\Code\NextBook\.env.local
info  - Creating an optimized production build
info  - Compiled successfully 
Warning: You have opted-out of Automatic Static Optimization due to `getInitialProps` in `pages/_app`. This does 
not opt-out pages with `getStaticProps`
Read more: https://err.sh/next.js/opt-out-auto-static-optimization

Usage example: NextBook

Always forcing dark mode even if I set the mode to light

I created a simple NextJS project to test this lib and I'm using MantineUI with dark mode active on my system. The implementation is like this:

// src/pages/_app.tsx
import { MantineProvider, MantineThemeOverride } from '@mantine/core';
import { useHotkeys } from '@mantine/hooks';
import withDarkMode, { MODE, useDarkMode } from 'next-dark-mode';
import { AppProps } from 'next/app';

function App({ Component, pageProps }: AppProps) {
  const { darkModeActive, switchToDarkMode, switchToLightMode } = useDarkMode();

  useHotkeys([['mod+J', darkModeActive ? switchToLightMode : switchToDarkMode]]);

  return (
    <MantineProvider 
      withGlobalStyles 
      withNormalizeCSS 
      theme={{ colorScheme: darkModeActive ? 'dark' : 'light' }}>
      <Component {...pageProps} />
    </MantineProvider>
  );
}

export default withDarkMode(App, { defaultMode: MODE.LIGHT });
// src/pages/index.tsx

export default function Index() {
  return 'Index'
}

When starting the project and opening the index page, dark mode is activated. If I use the key combination "CMD + J" (or "CTRL + J" on Windows), the theme will change to light mode, but if the page is refreshed, this change will not be kept.

How to solve this?

Can't make it work with React 18

Hi @xeoneux,

Thank you for this very nice module.
I have it setup in the demo repo of tss-react with Next.js but since upgrading to React 18 I can't make it work anymore.

Observed behavior:

When reloading the page, the mode automatically switches back to OS default.

Expected behavior:

The mode to be persisted across reload.

Steps to reproduce:

git clone https://github.com/garronej/tss-react
cd tss-react
yarn
yarn build
yarn start_ssr

Setup highlights:

Video demo

Screen.Recording.2022-05-21.at.02.41.25.mov

@Deckstar: Hello, would you be kind enough to confirm or infirm that next-dark-mode no longer work with React 18 + Next.js 12.1.7-canary.4 (or newer)?

Force dark mode

Hi there, is there a way to always force dark mode?
Allow switching but if the user reload => dark mode

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.