Search code examples
cssreactjsnext.jstailwind-cssdaisyui

I can't get daisyui's theme to propagate in a next.js app


I am trying to use a theme from "Daisyui" which is a tailwind based css component library https://daisyui.com/. I have a next.js app where the entry point is pages/_app.tsx. From looking at examples and reading the website's documentation, it looks like the theme is passed on from the highest component to all of the inwards components.

You add daisyui to the tailwind.config.js file, Like this:
enter image description here

I made my tailwind.config.js file look like this:

/** @type {import('tailwindcss').Config} */
module.exports = {
    //...
    content: ['./pages/**/*.{js,ts,jsx,tsx}'],
    plugins: [require("daisyui")],
    daisyui: {
      themes: true
    }
  }

true means that all the themes are included.

I added the theme "synthwave" to the highest level component of the next.js app which is a div tag wrapping around Component:

import '../styles/globals.css'
import type { AppProps } from 'next/app'

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <div theme-data="synthwave">
  <Component {...pageProps} />
  </div>
  )
}

export default MyApp

I also made a postcss.config.js file

module.exports = {
    plugins: ['tailwindcss', 'autoprefixer'],
  };

And I imported

@tailwind base;
@tailwind components;
@tailwind utilities;

at the top of globals.css.

This fails because the resulting webpage is just plain white.
enter image description here

But what's weird is when I change daisyui: { themes: true } in tailwind.config.js to daisyui: { themes: ["synthwave"] }. The webpage IS correctly themed with daisyui's synthwave:
enter image description here

I'm assuming that this only works because it's overriding ALL styles on every page and I don't want that. I want to be able to declare different themes on any page if I want to. So how do I correctly set the theme for the entire app in a way that I can override it on individual pages if I want?


Solution

  • This link is very helpful https://nextjs.org/docs/advanced-features/custom-document. You can make a file called _document.js that can update the and tags used to render a page. Just like the link says, I created a file called _document.js in pages that looks like this:
    pages/_document.js:

    import { Html, Head, Main, NextScript } from 'next/document'
    
    export default function Document() {
      return (
        <Html data-theme="synthwave">
          <Head />
          <body>
            <Main />
            <NextScript />
          </body>
        </Html>
      )
    }
    

    Notice this piece of code <Html data-theme="synthwave">. It correctly set index.tsx to daisyui's synthwave theme.