React Dark Mode - Flowbite

Learn how to configure and build a dark mode switcher for Flowbite using Tailwind CSS and start developing with the components from the library

Toggle dark mode#

Surround the contents of your app with the <Flowbite> component, and add the <DarkThemeToggle> component inside it. The <DarkThemeToggle> component will automatically detect the current theme and display the correct icon, and allow the user to switch between themes as they like.

import { DarkThemeToggle, Flowbite } from 'flowbite-react';

export default function MyPage() {
  return (
    <Flowbite>
      ...
      <DarkThemeToggle />
      ...
    </Flowbite>
  );
}

NextJS#

In server side rendered applications, such as NextJS, to avoid page flicker (if dark mode is set) before NextJS hydrates the content, ThemeModeScript component must be rendered in Head component (see implementation below).

ThemeModeScript renders a script tag that sets dark or removes dark from <html> element before hydration occurs.

App router#

// app/layout.tsx

import { ThemeModeScript } from 'flowbite-react';

export default function RootLayout({ children }) {
  return (
    <html>
      <head>
        <ThemeModeScript />
      </head>
      <body>{children}</body>
    </html>
  );
}

Pages router#

// pages/_document.tsx

import { ThemeModeScript } from 'flowbite-react';

export default function Document() {
  return (
    <Html>
      <Head>
        <ThemeModeScript />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}