Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 356
Wilson Avatar asked Oct 22 '25 15:10

Wilson


1 Answers

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

like image 100
BIRKAN Avatar answered Oct 25 '25 06:10

BIRKAN