1

I have a blog (http://minid.net) in Jekyll that I want to migrate to Next.js. My blog doesn't use an external file for styles. I embedded all the styles in the HEAD element using a STYLE element. In Next.js, i created a Style.js component, that returns body {} but that throws an error.

enter image description here

export default function Styles() {
  return <style>body{background: red;}</style>;
}

My blog benefits from not having to use external files, each generated HTML has its styles, so I don't want to use the traditional global stylesheet for Next.js.

How can I solve this?

10
  • What does the error say?
    – Kip
    May 13, 2022 at 16:15
  • 1
    You seem to think that having external files is a bad thing. Having all your styles in a css file means that the browser will cache the file and your rendered html will be smaller.
    – Lee Taylor
    May 13, 2022 at 16:15
  • 2
    Remember that it's a jsx that you're writing here, which is an extension of javascript and not html. Try using a backtick as part of string template literal.
    – Bumhan Yu
    May 13, 2022 at 16:31
  • 2
    Something like <style type="text/css">{`body {background-color: blue;}`}</style>
    – Bumhan Yu
    May 13, 2022 at 16:33
  • 1
    @BumhanYu this worked flawlessly. I hope it works with the SSR too! thanks!
    – Minide
    May 13, 2022 at 17:22

1 Answer 1

4

Take a read through this section of the docs: https://nextjs.org/docs/basic-features/built-in-css-support#css-in-js

In summary you have to put the children of the style element inside of a string enclosed in brackets.

export default function Styles() {
  return (
    <style jsx>{`
      body{
        background: red;
      }
    `}</style>;
}
2
  • 1
    I don't know how you're using the styles but you might also need to add the global property to the style component May 13, 2022 at 16:34
  • I found this info while reading the CSS implementation. This solution works but not for SSR github.com/WICG/webcomponents/issues/71
    – Minide
    May 13, 2022 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.