Component definition is missing display nameeslintreact/display-name | ESLint

Bori·2023년 12월 17일
0

어쨌든 공부

목록 보기
37/40

다음과 같이 forwardRef를 사용한 곳에서 eslint error가 발생했습니다.

const Container = React.forwardRef((props, ref) => {
    return <Component ref={ref} {...props} />;
};

export default Container;

Error message
Component definition is missing display name eslint(react/display-name)

react/display-name

displayName은 컴포넌트의 이름을 지정하여, React에서 디버깅을 용이하게 하기 위한 속성입니다.

forwardRef를 통해 ref를 자식 컴포넌트에 전달하여 그 내부의 HTML 요소에 접근할 수 있는데, forwardRef를 호출할 때 위와 같이 익명함수를 넘기게 되면 React 개발자 도구에서 해당 컴포넌트의 이름이 나오지 않습니다.
따라서, 이를 방지하기 위해 eslint error가 발생할 수 있습니다.

해결 방법

  1. forwardRef 호출 시 기명함수를 넘깁니다.
const Container = React.forwardRef(function DisplayNameComponent(props, ref) => {
    return <Component ref={ref} {...props} />;
};

export default Container;
  1. displayName 속성으로 컴포넌트 이름을 명시합니다.
const Container = React.forwardRef((props, ref) => {
    return <Component ref={ref} {...props} />;
};

Container.displayName = 'Container';
                                   
export default Container;
  1. forwardRef 호출의 결과를 다른 컴포넌트로 대체합니다.
const Container = (props, ref) => {
    return <Component ref={ref} {...props} />;
};
                                   
export default React.forwardRef(Container);

참고

0개의 댓글