All'alba vincerò

At dawn, I will win!

React

[React] 컴포넌트 속성(prop) 타입 검사(prop-types)

나디아 Nadia 2024. 8. 1. 17:30

📌 컴포넌트 속성 타입 검사(Prop Types Validation)

  • 컴포넌트는 정확한 마크업을 위해 외부로부터 전달받은 데이터인 속성(props)의 타입을 지정해야 한다.

 

1. 타입 스크립트 파일을 생성하여 타입 검사를 하나로 모아둔다.

// type.d.js
import { oneOf, arrayOf, exact, string } from 'prop-types';
import { IMAGE_TYPES, statusMessages } from '../data/learn';

export const StatusMessagesType = arrayOf(oneOf(statusMessages));

export const ImagesType = oneOf(IMAGE_TYPES);

export const ItemType = exact({
  id: string,
  message: string,
});

export const ItemsType = arrayOf(ItemType);

export const ReactLibraryType = exact({
  name: string,
  author: string,
  writtenIn: string,
  type: string,
  license: string,
});

 

 

2. 컴포넌트 파일에 타입 파일의 타입 검사를 가져와서 적용한다.

// render-lists.jsx
import { ItemsType, ReactLibraryType } from '../@types/types.d';

RenderLists.propTypes = {
  items: ItemsType.isRequired, 
  // [권장] arrayOf({ id: string, message: string }) | arrayOf(number)
  
  reactLibrary: ReactLibraryType.isRequired, 
  // [권장] shape()
};

 

 


 

 

📍 컴포넌트 속성 검사 라이브러리(prop-types)

 

prop-types 설치

 

  • 배포용
pnpm install --save prop-types


  • 개발용
pnpm add @types/prop-types -D

 

 

 


 

✅ 컴포넌트 속성 타입 지정

import PropTypes from 'prop-types';

컴포넌트명.propTypes = { 
     props명() {}
}

 

 

 

 

✅ PropTypes

 

prop를 특정 JS 형식으로 선언

  • 선택 사항
  • 배열, 불리언, 함수, 숫자, 문자열, 객체, 심볼
  optionalArray: PropTypes.array,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,

 

 

 

isRequired

: prop 필수 속성을 설정

  • 속성 값이 기본값으로 설정되어 있으면 사용 X
requiredFunc: PropTypes.isRequired,
requiredFunc: PropTypes.func.isRequired,

// 모든 데이터 타입이 가능한 필수값
requiredAny: PropTypes.any.isRequired,

 

 

 

 arrayOf()

:  배열의 요소가 특정 타입이어야 할 때 사용 

  • 배열이 특정 타입의 요소만 포함하도록 강제
import PropTypes from 'prop-types';

const MyComponent = ({ numbers }) => (
  <div>{numbers.join(', ')}</div>
);

MyComponent.propTypes = {
  numbers: PropTypes.arrayOf(PropTypes.number).isRequired,
};
// numbers는 PropTypes.arrayOf(PropTypes.number)를 통해 배열의 모든 요소가 숫자여야 한다는 것을 명시하고 있다.

 

 

 

 objectOf()

: 객체의 프로퍼티가 특정 타입 이어야 할 때 사용 

import PropTypes from 'prop-types';

const MyComponent = ({ data }) => (
  <div>{Object.keys(data).map(key => (
    <div key={key}>{key}: {data[key]}</div>
  ))}</div>
);

MyComponent.propTypes = {
  data: PropTypes.objectOf(PropTypes.string).isRequired,
};
// data는 PropTypes.objectOf(PropTypes.string)을 통해 객체의 모든 값이 문자열이어야 한다고 명시하고 있다.

 

 

 

⏩ oneOf()

: props가 정의된 특정한 값들 중 하나여야 한다고 정의할 때 사용

export const statusMessages = [
  '⌛️ 대기',
  '⏳ 로딩 중...',
  '✅ 로딩 성공!',
  '❌ 로딩 실패.',
];


import { oneOf, arrayOf } from 'prop-types';

DataBinding.propTypes = {
  statusMessages: arrayOf(oneOf(ststusMessages)).isRequired
};

 

 

 

⏩ oneOfType()

: props가 정의된 여러 타입 중 하나와 일치해야 한다고 정의할 때 사용

import PropTypes from 'prop-types';

const MyComponent = ({ data }) => (
  <div>{data}</div>
);

MyComponent.propTypes = {
  data: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.arrayOf(PropTypes.string),
  ]).isRequired,
};
// data는 문자열, 숫자, 또는 문자열 배열 중 하나여야 한다.

 

 

 

⏩ shape()
: 객체의 속성과 해당 속성들의 타입을 정의

  • 객체의 구조를 정의
  • 객체가 주어진 형태와 일치해야 한다고 정의한다.
  • 명시되지 않은 다른 속성은 검증하지 않는다. 
import PropTypes, { array, shape, string } from 'prop-types';

RenderLists.propTypes = {
  items: array, 

  reactLibrary: shape({
    name: string,
    author: string,
    writtenIn: string,
    type: string,
    license: string,
  }),
};

 

 

 

⏩ exact()

: 객체가 정의된 형태와 정확히 일치해야 함을 정의 

  • 객체의 구조를 엄격하게 정의
  • 명시된 속성 외에 다른 속성이 있으면 검증에 실패한다. 
  • 사용 권장 👍
import PropTypes, { array, exact, string } from 'prop-types';

RenderLists.propTypes = {
  items: array,

  reactLibrary: exact({
    name: string,
    author: string,
    writtenIn: string,
    type: string,
    license: string,
  }), 
};

 

 

 

⏩ PropTypes.element

: 컴포넌트의 자식들 중 단 하나의 자식만 전달될 수 있도록 명시

MyComponent.propTypes = {
  children: PropTypes.element.isRequired
};

 

 

 

⏩ defaultProps

: props의 초깃값 정의

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

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

const root = ReactDOM.createRoot(document.getElementById('example')); 
root.render(<Greeting />); // "Hello, Stranger"

 

 


 

 

prop-types

Runtime type checking for React props and similar objects.. Latest version: 15.8.1, last published: 3 years ago. Start using prop-types in your project by running `npm i prop-types`. There are 58174 other projects in the npm registry using prop-types.

www.npmjs.com

 

 

prop-types-exact

For use with React PropTypes. Will error on any prop not explicitly specified.. Latest version: 1.2.5, last published: 23 days ago. Start using prop-types-exact in your project by running `npm i prop-types-exact`. There are 81 other projects in the npm reg

www.npmjs.com

 

 

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

A JavaScript library for building user interfaces

ko.legacy.reactjs.org