Next.js - styled-components error 해결

ryan·2022년 6월 20일
0

Prop 'className' did not match

  • Next.js에서 styled-component를 적용하고 렌더링을 시키니 위와 같은 에러가 발생했다.

에러 발생 원인

  • 이러한 에러가 발생한 이유는 첫 화면 렌더링은 SSR이고, 이후 페이지 이동 시 발생하는 렌더링은 CSR이기 때문에 서버/클라이언트 간의 ClassName의 차이가 발생하기 때문이다.
  • 아래 에러 메시지에서 더 자세히 확인할 수 있다.
Warning: Prop `className` did not match.
server: "sc-ftvSup lFHmx" Client: "sc-dkzDqf dTlXpN"

해결 방법

  • babel-plugin-styled-components을 설치한다.

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

  • 아래와 같이 .babelrc 파일 생성 후 plugin을 추가해준다.
{
  "plugins": ["babel-plugin-styled-components"]
}

babel-plugin-styled-components

  • NPM에서의 설명
    consistently hashed component classNames between environments (a must for server-side rendering)

  • 환경 간 일간된 hashed className을 제공한다.(서버 사이드 렌더링에서 필수적이다.)

  • 위 참고한 자료에서 더 자세한 설명이 나와있다.

    컴포넌트가 생성되는 순서에 따라 같은 컴포넌트이더라도 다른 식별자가 붙을 수 있게 된다. SSR과 CSR을 같이 활용하는 경우 서버와 클라이언트가 컴포넌트를 생성하는 순서에 따라 식별자가 달라질 수 있다.

profile
프론트엔드 개발자

0개의 댓글