DEV Community

Cover image for Next.js + Styled Components The Really Simple Guide ▲ + 💅

Next.js + Styled Components The Really Simple Guide ▲ + 💅

Adrian Prieto on June 27, 2018

I recently started using Next.js, and quite honestly I have to say, is an awesome tool, you get a lot out of the box, and while there are some thin...
Collapse
 
blelem profile image
Berthier Lemieux

Thanks, this was really useful.

Let me add some SEO for people google for their Next + styled-component issues. Adding the babel configuration .babelrc in step 5 will fix the following errors/warnings:

Warning: Prop `className` did not match. Server: "sc-htpNat kRxhCE" Client: "sc-bdVaJa gCHvCg"
Enter fullscreen mode Exit fullscreen mode
It looks like you've wrapped styled() around your React component (Component), but the className prop is not being passed down to a child. No styles will be rendered unless className is composed within your React component.
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mtrabelsi profile image
Marwen Trabelsi • Edited

not really working, here explanation:
it only works for the first load, if you hard reload + remove cach, then it crashes and keeps crashing

Collapse
 
noncototient profile image
Bo • Edited

Thanks mate, worked beautifully with the latest version of NextJS (v7)

Edit: actually, results in this annoying error:

Warning: Prop `className` did not match.
Enter fullscreen mode Exit fullscreen mode

Any ideas? GitHub issues and Google are not helping.

Collapse
 
cedricgourville profile image
Cédric Gourville • Edited

yes 2 years later

.babelrc


{
   "env": {
      "development": {
         "plugins": [
            [
               "styled-components",
               { "ssr": true, "displayName": true, "preprocess": false }
            ]
         ],
         "presets": ["next/babel"]
      },
      "production": {
         "plugins": [
            [
               "styled-components",
               { "ssr": true, "displayName": true, "preprocess": false }
            ]
         ],
         "presets": ["next/babel"]
      }
   },
   "plugins": [
      [
         "styled-components",
         { "ssr": true, "displayName": true, "preprocess": false }
      ]
   ]
}


Enter fullscreen mode Exit fullscreen mode
Collapse
 
nicklima profile image
Nick Lima

Thanks for the post. It helped me a lot in the past.

I'm here to thank you and to say for the future users looking for styled-components on Next.js that now with the new Next.js 12 version, you can handle the styled-components natively in next-config file:

// next.config.js

module.exports = {
  compiler: {
    // ssr and displayName are configured by default
    styledComponents: true,
  },
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
matheusdamiao profile image
Matheus Damião

Thank you! That was a huge saving!

Collapse
 
bbynog profile image
bbynog

thank you!

Collapse
 
quadsurf profile image
Chris Castro • Edited

chrome user agent stylesheet annoyingly has a default margin of 8px around my website... how/where do you add body css to override that globally? I tried using/importing { createGlobalStyle } from 'styled-components' but that didn't seem to work, probably because my implementation was all trial and error guessing

"""const GlobalStyle = createGlobalStyle
body {
margin: 0
}
"""
i then wrapped the above component around my app, and all it did was make the contents of my app disappear like whiteout :-(

also, github.com/vercel/next.js/tree/mas... offers no explanation on how/where to inject global css

Collapse
 
wynxnyw profile image
Kyle Winkler

Well one major issue is you shouldn't wrap your app with the GlobalStyle component.
This is a common mistake actually, but you'll notice that GlobalStyle isnt a react component and it does not take children as a prop so anything inside won't be rendered.

Instead you need to render it as a self closing tag <GlobalStyle />

Collapse
 
normancarcamo profile image
Norman Enmanuel

The solution to this problem is using the updated version of the pages/_document.js file.
github.com/vercel/next.js/blob/mas...

Collapse
 
susannelundblad profile image
Susanne Karin Lundblad

Hi! When adding <title> to the _document.js file I get an error

Warning: <title> should not be used in _document.js's <Head>. https://err.sh/next.js/no-document-title

Collapse
 
pjaws profile image
Paul Matthew Jaworski

That's absolutely right. You should put it in next/head instead.

Collapse
 
ahikmatf profile image
Asep Hikmat Fatahillah • Edited

I am using latest NextJS (8.0.3) and Styled-Components (4.1.3) and seems like it doesn't need to extend the <Document /> component anymore (step 6), because I don't see any error(?)

edit: Nope, my fault. Step 6 will make the page's style rendered before being served in the browser, so there will be no flash of unstyled content

Collapse
 
mustafaturk profile image
Mustafa Türk • Edited

Thanks!

Is there a specific reason for installing babel-plugin-styled-components as a dev dependency, since you are not using it anywhere? Or am I missing something here?

Collapse
 
sfkiwi profile image
Mike Sutherland

Thanks, really useful. Solved the issues I was running into

Collapse
 
janpauldahlke profile image
jan paul

sorry to comment so late on this man. dont know if you will even read this.

do you have some experiences how much your steps 1- 4 in

MyDocument extends Document

would impact speed, in terms of build time?

i mean is styled components still i thing in react nowadays? i moved to angular and am tinkering on next in spare time, but did not quiete like tailwinds bootstrappy approach

Collapse
 
jefdavis54 profile image
Jeff • Edited

This was a useful starting point, but I found that Next.js maintains an example that is more up to date. Check it out here...

Collapse
 
aprietof profile image
Adrian Prieto

Hey Jeff, you are probably right, Next.js has made so many great changes since I wrote this post, that I'm not surprised this is no longer up to date, I would definitely suggest to follow their documentation. Thanks for the heads up. By the way what are the main changes?

Collapse
 
jonatasoc profile image
Jonatas de Oliveira Coêlho • Edited

Hey, Adrian! This is exactly what I was looking for. Thanks!

Do you guys try to use it with Typescript?

I get an error on {this.props.styleTags} and I don't now how to type the class correctly to understand it as part of the MyDocument.

Collapse
 
adammescher profile image
Adam Mescher

Solved my issues. Thanks for laying all of this out in such a complete and understandable way.

Collapse
 
eliasmqz profile image
Anthony Marquez

thanks for this mate really saved my bacon

Collapse
 
annlin profile image
ann lin

are we able to move const sheet = new ServerStyleSheet(); out of the class? so we just create an instance of ServerStyleSheet instead of creating new one every time we render a page?

Collapse
 
julioflima profile image
Julio Lima

Amazing the configuration of ".babelrc" was not working with the default configuration of provided by styled components, something related with works just in CRA.

I'll add something... "styled-components" already have the "babel-plugin-styled-components" so you don't need to install.

Collapse
 
timknapp12 profile image
Tim Knapp

Thanks! That was very helpful and very easy to follow along! Worked like a charm

Collapse
 
aprietof profile image
Adrian Prieto

I'm glad! good luck with everything!

Collapse
 
theomer profile image
TheoMer

Is it possible to do strict (nonce) csp (content security policy) with next/styled components?

Collapse
 
beatlecz profile image
beatlecz • Edited

Great post! Works like a charm on Next 8 ... Thank you!

Collapse
 
eliastouil profile image
eliastouil

Your article was really useful to me.
With styled-components 3.3.3 i'm unable to use injectGlobal, any thoughts or example ?
Thanks :)

Collapse
 
creativehubspace profile image
Dennis Mathenge

injectGlobal has been replace with a createGlobalStyle component. Read more about it here:
styled-components.com/docs/faqs#wh...

Collapse
 
quickshiftin profile image
Nathan Nobbe

It seems to be applying the CSS client side. The page loads without any styling, then a second later styles are applied...

I suppose this solution does not work well in conjunction with styled-jsx?

Collapse
 
allexon profile image
Alexon da Silva Moreira

so how would I do with REACT + NEXT + STYLED-COMPONENT to put a css background image
how I use this css with next -> backound-image> url ('........')

Collapse
 
hummingbird profile image
Tito

Thank you for this, very well written and to the point!

Collapse
 
ahmedmuhsingez profile image
AhmedMoh

Hey.. any help with the className problem? Couldn't solve it any way..

Collapse
 
holdmypotion profile image
Rahul

You saved me. Thanks!

Collapse
 
gaddmaster profile image
Daniel Gadd • Edited

What about the error
error The mandatory attribute 'amp-custom' is missing in tag 'style amp-custom'
This article either has to be depreciated or updated to support amp

Collapse
 
jkntji profile image
Jai

nextjs seems to have native support for styled components now, didn't need any of the steps mentiond here.

Collapse
 
oliverloops profile image
Oliver Lopez

So helpful! 🎉🎉🎉

Collapse
 
fighella profile image
Jonny Dalgleish

Thanks so much for this. :)