I have a blog () 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 ponent, that returns body {} but that throws an error.
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?
I have a blog (http://minid) 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 ponent, that returns body {} but that throws an error.
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?
Share Improve this question edited May 13, 2022 at 16:17 Minide asked May 13, 2022 at 16:08 MinideMinide 3051 gold badge5 silver badges17 bronze badges 10- What does the error say? – Kip Commented 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 Commented May 13, 2022 at 16:15
-
2
Remember that it's a
jsx
that you're writing here, which is an extension ofjavascript
and nothtml
. Try using a backtick as part of string template literal. – Bumhan Yu Commented May 13, 2022 at 16:31 -
2
Something like
<style type="text/css">{`body {background-color: blue;}`}</style>
– Bumhan Yu Commented May 13, 2022 at 16:33 - 1 @BumhanYu this worked flawlessly. I hope it works with the SSR too! thanks! – Minide Commented May 13, 2022 at 17:22
2 Answers
Reset to default 5Take a read through this section of the docs: https://nextjs/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>;
}
you can use dangerouslySetInnerHTML
define the styles
const style = `<style>
body{color: blue; font-size: 18px;}
</style>`
and then put it anywhere in your page
<span dangerouslySetInnerHTML={{ __html: style }} />