Cambiare tema in Next.js con next-themes

Mattepuffo's logo
Cambiare tema in Next.js con next-themes

Cambiare tema in Next.js con next-themes

next-themes è un hook per Next.js che ci permette di passare dal tema dark/light in maniera abbastanza facile.

In questo articolo vediamo come usarlo.

Per l'installazione possiamo usare npm:

npm install next-themes

Io poi ho usato una Custom App, quindi ho creato il file pages/_app.tsx (o pages/_app.js a se usate Javascript e non Typescript) con questo dentro:

import {ThemeProvider} from 'next-themes';

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

export default MyApp;

Un pò di CSS:

:root {
  /* SETTATE IL TEMA DI DEFAULT */
  --background: white;
  --foreground: black;
}

[data-theme='dark'] {
  --background: black;
  --foreground: white;
}

In fine creaiamo un componente per lo switcher:

import {useTheme} from 'next-themes';

const ThemeSwitcher = () => {
  const {theme, setTheme} = useTheme();

  return (
    <div>
      Tema corrente: {theme}
      <button onClick={() => setTheme('light')}>Light Mode</button>
      <button onClick={() => setTheme('dark')}>Dark Mode</button>
	  <button onClick={() => setTheme('system')}>System Mode</button>
    </div>
  );
}

Enjoy!


Condividi

Commentami!