10

I'm trying to implement styled-components in a React project with Nextjs. The problem is that, although I can implement and see the styles, there is a small delay when I see it on the browser. First it loadeds the component without style, and 22ms later the style is applied. What I'm doing wrong? Thanks

Here is my code!

pages/index.js

import React from "react";
import Home from "../components/home/index";


const index = () => {
  return (
    <React.Fragment>
        <Home />
    </React.Fragment>
  );
};

export default index;

components/home.js

import React from "react";
import styled from 'styled-components';

const Title = styled.h1`
  color: red;
`;

function Home() {
  return (
    <div>
      <Title>My First Next.js Page</Title>
    </div>
  );
}

export default Home;

babel.rc

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}

pages/_document.js

import Document from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        )
      };
    } finally {
      sheet.seal();
    }
  }
}
larry_82
  • 319
  • 1
  • 4
  • 15

2 Answers2

6

This happens because your styles are being applied client side. You will need to follow this modification from the examples provided by Next.js.

You actually need to create a custom Document, collect all your styles from your <App /> component using ServerStyleSheet provided by styled-components and apply them server side, so when your app reaches the client, the styles will already be there.

As they also state on the README of this example:

For this purpose we are extending the <Document /> and injecting the server side rendered styles into the <head>, and also adding the babel-plugin-styled-components (which is required for server side rendering).

I hope this solves your issue.

Michalis Garganourakis
  • 2,872
  • 1
  • 11
  • 24
1

Here is an example of the _document file:

import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static getInitialProps({ renderPage }) {
    const sheet = new ServerStyleSheet();

    function handleCollectStyles(App) {
      return props => {
        return sheet.collectStyles(<App {...props} />);
      };
    }

    const page = renderPage(App => handleCollectStyles(App));
    const styleTags = sheet.getStyleElement();
    return { ...page, styleTags };
  }

  render() {
    return (
      <html>
        <Head>{this.props.styleTags}</Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

I hope this helps!

German
  • 557
  • 3
  • 5
  • I German, thanks! I try your example and the loader time reducer form 22 to 11 ms, but the problem still there... – larry_82 Jan 10 '20 at 02:17
  • Oh that's great, do you have a repo of your code? I can take a look to check the issue. – German Jan 10 '20 at 02:23
  • I found the issue, the file should be named **_document.js** and not **_documents.js** just rename the file and paste my code into your **_document.js** and it should work! I cloned your code and made those changes and it worked! let me know. – German Jan 10 '20 at 16:00
  • No problem :) Glad i helped! – German Jan 10 '20 at 18:38