sanguk.dev
작성완료
NextJS Prop `className` did not match 이슈

NextJS Prop `className` did not match 이슈

styled-components 모듈 사용 시 서버와 클라이언트에서 생성된 className이 다르게 되어 발생하는 이슈에 대한 해결 방법을 제시. NextJS 13버전 미만에서는 babel-plugin-styled-components를 추가하고 설정 파일을 수정해야 하며, 13버전 이상에서는 next.config.js에 SSR 설정을 추가해야 함.

NextJSstyled-components

원인

styled-components모듈을 사용 할 때 서버에서 생성된 className과 클라이언트에서 생성된 className이 서로 다른 것 때문에 뜨는 이슈이다.

콘솔 결과

해결 방법1 (NextJS 13버전 미만)

plain
yarn add -D babel-plugin-styled-components

/.babelrc

javascript
{
  "plugins": [
    [
      "babel-plugin-styled-components",
      {
        "displayName": true,// 클래스명에 컴포넌트 이름을 붙임"pure": true,// 사용되지 않는 속성 제거"ssr": true// SSR을 위한 설정
      }
    ]
  ]
}

해결 방법2 (NextJS 13버전 이상)

/next.config.js

javascript
/** @type {import('next').NextConfig} */const nextConfig = {
  compiler: {
    styledComponents: {
      ssr: true
    },
  },
};

module.exports = nextConfig;