에러일지

Eslint: Function component is not a function declaration(react/function-component-definition)

맑쇼 2024. 3. 12. 18:10
반응형
Eslint: Function component is not a function declaration(react/function-component-definition)

 

원인

  리액트는 보통 함수형 컴포넌트를 사용한다. react/function-component-definition 규칙을 사용하려면, 이 함수형 컴포넌트를 어떤 함수 유형으로 사용할지 미리 정하고, .eslintrc의 rules에 명시해두어야 에러가 발생하지 않는다.

해결

함수 유형에 따른 함수 유형을 지정해주어야 한다.

// 타입1 : 기명함수 선언식 컴포넌트
// "react/function-component-definition": [
//   2, {"namedComponents" : "function-declaration" }] 
 
   function Component (props) {
   return <div />;
 }
// 타입2 : 기명함수 표현식 컴포넌트
/* "react/function-component-definition": [
  2, {"namedComponents" : "function-expression" }] */
  
const Component = function (props) {
 return <div />;
 }
// 타입3 : 기명함수 화살표 함수 컴포넌트
/* "react/function-component-definition": [
  2, {"namedComponents" : "arrow-function" }] */
 
const Component = (props) => {
 return <div />;
 }
// 타입4 : 익명함수 표현식 컴포넌트
/* "react/function-component-definition": [
  2, {"namedComponents" : "function-expression" }] */
 
function getComponent() {
  return function (props) {
   return <div />;
   }
  }
// 타입5 : 익명 화살표 함수 컴포넌트
/* "react/function-component-definition": [
  2, {"namedComponents" : "arrow-function" }] */
 
function getComponent() {
  return (props) => {
   return <div />;
   }
  }

 

위의 5가지 유형 중 사용할 유형을 .eslintrc의 rules에 적어준다. 보통 1과 3번의 유형을 많이 사용하므로 아래와 같이 추가하면 된다.

"rules": {
    "react/function-component-definition":[
      2,
      { "namedComponents": [
        "arrow-function",
        "function-declaration"
      ] }
    ]

 

반응형