tech

[React] PropTypes

Siyoon Jeon 2021. 11. 28. 12:50

What?

PropTypes란, 특정 애플리케이션에서 전체 애플리케이션의 타입 검사를 위해 TypeScript와 같은 JavaScript 도구이다. 이름에서부터 TypeScript와 굉장히 비슷한 느낌이 들었는데, 아니나 다를까 공식문서에도 그렇게 소개를 하고 있다. React.PropTypes는 React v15.5부터 다른 패키지로 이동하여 prop-types 라이브러리를 사용하길 권장하고 있다.

 

Why?

앱이 커짐에 따라 타입 검사를 활용한다면 버그를 잡을 수 있다.

 

How?

설치

npm i prop-types

import

import PropTypes from "prop-types";

기본 사용 방법

import PropTypes from 'prop-types';

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

Greeting.propTypes = {
  name: PropTypes.string
};
  • 렌더링 될 수 있는 것들 : 숫자, 문자, 엘리먼트, 또는 이러한 타입들을 포함하고 있는 배열
  • React 엘리먼트 : PropTypes.element
  • React 엘리먼트 타입 : PropTypes.elementType
  • prop가 클래스의 인스턴스임을 선언하는 경우 : PropTypes.instanceOf(Message)
  • 여러 종류 중 하나의 종류가 될 수 있는 객체 : PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(Message) ])
  • 특정 타입의 행렬 : PropTypes.arrayOf(PropTypes.number)
  • 특정 타입의 프로퍼티 값들을 갖는 객체 : PropTypes.objectOf(PropTypes.number)
  • 특정 형태를 갖는 객체 : PropTypes.shape({ color : PropTypes.string, fontSize : PropTypes.number })
  • 추가 프로퍼티에 대한 경고가 있는 객체 : PropTypes.exact({ name : PropTypes.string, quantity : PropTypes.number })
  • 위 예시 모두 `isRequired` 와 연결하여 prop이 제공되지 않았을 때 경고가 보이도록 할 수 있다
    • PropTypes.func.isRequired
    • PropTypes.any.isRequired
  • 하나의 자식만 요구하기 
import PropTypes from 'prop-types';

class MyComponent extends React.Component {
  render() {
    // 이것은 반드시 하나의 엘리먼트여야 합니다. 아니라면, 경고(warn)가 일어날 것입니다.
    const children = this.props.children;
    return (
      <div>
        {children}
      </div>
    );
  }
}

MyComponent.propTypes = {
  children: PropTypes.element.isRequired
};
  • 초기 Prop 값 (defaultProps 프로퍼티를 할당함으로써 props의 초깃값을 정의할 수 있다.)
class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

// props의 초깃값을 정의합니다.
Greeting.defaultProps = {
  name: 'Stranger'
};

// "Hello, Stranger"를 랜더링 합니다.
ReactDOM.render(
  <Greeting />,
  document.getElementById('example')
);

 

  • 함수 컴포넌트
import PropTypes from 'prop-types'

function HelloWorldComponent({ name }) {
  return (
    <div>Hello, {name}</div>
  )
}

HelloWorldComponent.propTypes = {
  name: PropTypes.string
}

export default HelloWorldComponent

 


[ 참고한 자료 ]

https://ko.reactjs.org/docs/typechecking-with-proptypes.html

 

PropTypes와 함께 하는 타입 검사 – React

A JavaScript library for building user interfaces

ko.reactjs.org