简体   繁体   中英

How can I add a stylesheet dynamically with NextJS?

In my nextJS application, I need to load a stylesheet dynamically based on the user preference received from the database.

So, in my page, I'm adding it in the Head (next/head), as follows:

<Head>
<link rel="stylesheet" href={`/fonts/${type}/stylesheet.css`}></link>
</Head>

However, this is giving me a warning in the console in development mode:

Do not add stylesheets using next/head (see <link rel="stylesheet"> tag with href="/fonts/cal/stylesheet.css"). Use Document instead. 
See more info here: https://nextjs.org/docs/messages/no-stylesheets-in-head-component

The stylesheet itself contains the font-face:

@font-face {
  font-family: "Cal Sans";
  src: url("CalSans-SemiBold.woff2") format("woff2"),
    url("CalSans-SemiBold.woff") format("woff");
  font-weight: 600;
  font-style: normal;
  font-display: swap;
}

Since the user's preference is stored in the database, and I receive this value via a query, I don't know how I can add it to the Document.js file.

I'll really appreciate any help on this.

While it might be possible to dynamically import a CSS file in your main app component (and you can check out an example in this guide ), I would suggest a different solution.

Include all stylesheets in your application, but make its styles only apply when the html (or body ) element has a certain class. Then all you need to do is modify that class based on user preference.

// styles.css
body.themeFoo #container {
  // some styles...
}

This is how many implementations of dark mode work, eg in tailwind CSS. I believe this is a better pattern to solve your problem.

next.js uses react so maybe try the useState hook or you can change the herf property

import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html>
      <Head>
        <link rel="stylesheet" href="..." />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM