Wilson
Wilson

Reputation: 41

NextJS with styled-components fast refresh not working

I have a NextJS app being used with styled-components.

I have these 3 files: Worth noting that some markups are removed for clarity sake so only the related codes are pasted.

Header.js

import {
   HeaderContainer, 
   SearchInput,
   SearchWrapper
} from './HeaderStyles';
import { Input } from '../GlobalComponents/GlobalComponents';


const Header = () => {
   return (
      <HeaderContainer>
         <SearchWrapper>
            <SearchInput type='text' placeholder='Search movie' />
         </SearchWrapper>
      </HeaderContainer>
   );
}
 
export default Header;

HeaderStyles.js

import styled from 'styled-components';
import { Input } from '../GlobalComponents/GlobalComponents';

export const HeaderContainer = styled.header`
   background-color: ${props => props.theme.colors.primary};
   display: flex;
   align-items: center;
   box-sizing: border-box;
`;

export const SearchWrapper = styled.div`
   flex-grow: 3;
   background-color: red;
`;

export const SearchInput = styled(Input)`
   background-color: yellowgreen;
`;

GlobalComponents.js

import styled from "styled-components";

export const Input = styled.input`
   padding: 1rem;
`;

Attached is my Project Structure


Note that inside HeaderStyles.js, the SearchInput is extended from Input in GlobalComponents.js Whenever I change css properties in HeaderStyles.js, the fast refresh works just fine. However, in the case of GlobalComponents.js, I had to manually reload the page to view the changes.

If I were to put my generic Input styling into HeaderStyles, it works fine, but that isn't how I wanted to structure it. So I guess it somewhat related to the imported modules not being in the React tree or stuff like that.

I have been looking for solutions online but got no luck. Would like to know the causes and solution for this. Thanks in adv.

Upvotes: 4

Views: 7929

Answers (5)

Code ninja
Code ninja

Reputation: 190

The issue here is with Next JS and to resolve this you only need to add this code to _document.tsx or _document.js and it will be resolved

import Document, { DocumentContext } from "next/document";
import { ServerStyleSheet } from "styled-components";

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    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();
    }
  }
}

Upvotes: 1

Alin Codrut
Alin Codrut

Reputation: 27

I had the same issue.

First you have to install this package:

npm install --save-dev babel-plugin-styled-components

Then you create a file in the root of your project directory, by the name of "babel.config.js" In this file you will include the following:

module.exports = {
  presets: ["next/babel"],
  plugins: [["styled-components", { ssr: true }]]
};

Upvotes: 2

Abhishek Prajapati
Abhishek Prajapati

Reputation: 106

Make sure you have pages/_document.js with codes stated here.

Upvotes: 0

Valeria Daffarra
Valeria Daffarra

Reputation: 21

with the Next Complier on new version of next, you should only update your next.config file and _document file, and you will be all set. Babel will cause conflict with the NextJS compiler.

https://github.com/vercel/next.js/tree/canary/examples/with-styled-components

Upvotes: 1

BIRKAN
BIRKAN

Reputation: 81

I think your problem about styled-component at SSR.

You can try change your pages/_document.js and your babel config.

add this codes to .babelrc

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

_document.js

https://github.com/vercel/next.js/blob/main/examples/with-styled-components/pages/_document.js

Upvotes: 2

Related Questions