Home > Back-end >  How can I add a stylesheet dynamically with NextJS?
How can I add a stylesheet dynamically with NextJS?

Time:04-19

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.

CodePudding user response:

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, e.g. in tailwind CSS. I believe this is a better pattern to solve your problem.

CodePudding user response:

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

  • Related