본문 바로가기
리액트(React)

[React] 유용한 Prop-Types 활용하기

by 즐거운코딩 2024. 11. 12.
반응형

리액트에서 컴포넌트의 props에 대한 타입 검사를 제공하는 중요한 기능입니다.

 

PropTypes의 주요 장점과 기능은 다음과 같습니다.

 

1.  주요 장점

  • 타입 안정성 향상 - 컴포넌트에 전달되는 props의 타입을 런타임에 발견함으로써 조기에 오류 발견 가능
  • 코드 가독성 향상 - 컴포넌트에 어떤 타입의 props을 전달하면 되는지 명확히 지정
  • 디버깅 용이성 - 잘못된 타입의 props가 전달시 경고메시지 통해서 디버깅을 용이하게 함

2.  기능

  • 다양한 타입 검사 - 문자열, 숫자, 불리언, 배열, 함수 등 javascript 타입 검사 가능
  • 필수 props 지정 - 'isRequired' 로 필수 입력 값임을 명시
  • 복잡한 타입 검사 - 'oneof', 'oneOfType', 'arrayOf' 등 사용하여 복잡한 타임 검사 가능
  • 초기값 지정 - 'defaultProps' 지정으로 props 미지정시 표출될 값을 사전 지정 가능
  • 아래는 React 공식 페이지에 나오는 실제 사용 예시이므로 사용시 참고
MyComponent.propTypes = {
  // You can declare that a prop is a specific JS type. By default, these
  // are all optional.
  optionalArray: PropTypes.array,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,

  // Anything that can be rendered: numbers, strings, elements or an array
  // (or fragment) containing these types.
  optionalNode: PropTypes.node,

  // A React element.
  optionalElement: PropTypes.element,

  // A React element type (ie. MyComponent).
  optionalElementType: PropTypes.elementType,

  // You can also declare that a prop is an instance of a class. This uses
  // JS's instanceof operator.
  optionalMessage: PropTypes.instanceOf(Message),

  // You can ensure that your prop is limited to specific values by treating
  // it as an enum.
  optionalEnum: PropTypes.oneOf(['News', 'Photos']),

  // An object that could be one of many types
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),

  // An array of a certain type
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

  // An object with property values of a certain type
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),

  // An object taking on a particular shape
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  }),

  // An object with warnings on extra properties
  optionalObjectWithStrictShape: PropTypes.exact({
    name: PropTypes.string,
    quantity: PropTypes.number
  }),   

  // You can chain any of the above with `isRequired` to make sure a warning
  // is shown if the prop isn't provided.
  requiredFunc: PropTypes.func.isRequired,

  // A required value of any data type
  requiredAny: PropTypes.any.isRequired,

  // You can also specify a custom validator. It should return an Error
  // object if the validation fails. Don't `console.warn` or throw, as this
  // won't work inside `oneOfType`.
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },

  // You can also supply a custom validator to `arrayOf` and `objectOf`.
  // It should return an Error object if the validation fails. The validator
  // will be called for each key in the array or object. The first two
  // arguments of the validator are the array or object itself, and the
  // current item's key.
  customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
    if (!/matchme/.test(propValue[key])) {
      return new Error(
        'Invalid prop `' + propFullName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  })
};


class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

// Specifies the default values for props:
Greeting.defaultProps = {
  name: 'Stranger'
};

 

위와 같이 PorpTypes 는 대규모 프로젝트나 여러 개발자가 협업이 필요한 경우 오류 발생을 최소화 하기 위해 필요한 라이브러리 입니다. 하지만 근복적인 해결을 위해 타입스크립트를 사용하는 것을 권고합니다.

 

 

반응형