본문 바로가기

Front-end/React

React - PropTypes란?

PropTypes 사용하기

기본 사용법

import PropTypes from 'prop-types';

const Greeting = ({ name }) => {
  return (
    <h1>Hello, {name}</h1>
  );
}

Greeting.propTypes = {
  name: PropTypes.string
};

isRequired

.isRequired를 types뒤에 붙여주면 필수 prop으로 인식하고, 값이 없거나 잘못되었을 경우 콘솔 창에서 오류를 확인할 수 있다.

Greeting.propTypes = {
  name: PropTypes.string.isRequired
};

복잡한 배열이나 객체

string이나 number같은 원시자료형의 경우 PropTypes를 위 기본 사용법처럼 그대로 써도 문제가 없다. 하지만 array나 object의 경우, 같은 방식으로 사용한다면 eslint에서 경고가 나타난다. prop을 좀 더 명시적으로 나타내라는 의미같다.

array는 arrayOf로, object는 shape나 objectOf로 대체할 수 있다.

import PropTypes from 'prop-types';

const Greeting = ({ data }) => {
  return (
    {data.map(({ name, age }) => {
      <span key={name}>Hello, My name is {name}, I'm {age} years old.<span/>
    }};
  );
}

Greeting.propTypes = {
   data: PropTypes.arrayOf(
    PropTypes.shape({
      name: PropTypes.string.isRequired,
      age: PropTypes.number.isRequired
    }),
  ).isRequired
};

 

defaultProps

ES6에 기본 매개변수가 이미 있지만, PropTypes에서도 이를 사용할 수 있다. 후자가 React에서 기본 매개변수에 대해 타입 체킹을 해주므로 더 바람직한 방법이라고 한다. 그리고 isRequired를 사용하지 않았을 때, defaultProps가 설정돼있지 않다면 eslint에서 경고가 나타난다.

import PropTypes from 'prop-types';

const Greeting = ({ name }) => {
  return (
    <h1>Hello, {name}</h1>
  );
}

// 여기까지의 코드에서는 기본값이 설정돼있지 않다고 eslint가 경고를 나타낸다. 
Greeting.propTypes = {
  name: PropTypes.string
};

// defaultProps로 기본값을 설정해줄 수 있다.
Greeting.defaultProps = {
  name: "Octocat"
};

'Front-end > React' 카테고리의 다른 글

React Life Cycle 정리  (0) 2021.07.26
React - React-Router란?  (0) 2021.06.28
React - useFetch란?  (0) 2021.06.28
React - useReducer란?  (0) 2021.06.24
useRef 란 ?  (0) 2021.06.23