Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styled-components delay setting property in Nextjs

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();
    }
  }
}
like image 801
larry_82 Avatar asked Jan 09 '20 21:01

larry_82


2 Answers

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.

like image 167
Michalis Garganourakis Avatar answered Sep 18 '22 15:09

Michalis Garganourakis


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!

like image 42
German Avatar answered Sep 19 '22 15:09

German