next.js icon indicating copy to clipboard operation
next.js copied to clipboard

Global styles not applied until page refresh

Open thisbejim opened this issue 9 years ago • 4 comments

When applying global styles to a custom document the styles are not applied until you refresh the page, example:

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

export default class MyDocument extends Document {
  render () {
    return (
      <html>
        <Head>
          <meta charSet="utf-8" />
          <meta name="viewport" content="initial-scale=1.0, width=device-width" />
          <style jsx global>{`.welcome { color: red; }`}</style>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
};

index.js

export default () => (
  <div className="welcome">Welcome to next.js!</div>
)

If you close your localhost tab, npm run dev, then open up a fresh tab you will get this: snip20170126_1

If you refresh the page you get this: snip20170126_2

This also happens when you serve a production build of the project.

thisbejim avatar Jan 25 '17 20:01 thisbejim

Not exactly sure about how this happens. But you should not styles like this with the custom document. Whole purpose of the custom document should to customize your HTML page. Inside the custom layout, we don't have access to the React app.

So, try to move your styles to a common layout. See this related discussion: https://github.com/zeit/next.js/issues/873#issuecomment-275008448

arunoda avatar Jan 26 '17 02:01 arunoda

@arunoda actually we've seen this before. using styled-jsx inside of <Head> is not supported. Since it won't render an element. In this case styled-jsx is obsolete since <style>{.welcome { color: red; }}</style> will be global. Using just the <style> fixes your issue 👍

timneutkens avatar Jan 28 '17 20:01 timneutkens

I fixed with