<React> prop-types(package)

김민석·2021년 2월 18일
0

React

목록 보기
6/18

prop-types라고 하는 package에 대해 알아보겠습니다.

설치

%npm i prop-types

prop-types란?

Runtime type checking for React props and similar objects.You can use prop-types to document the intended types of properties passed to components. React (and potentially other libraries—see the checkPropTypes() reference below) will check props passed to your components against those definitions, and warn in development if they don’t match.
prop-types 공식 문서

Component에 props를 전달하면서 전달해야할 것을 전달하지 않는다던가 type을 헷갈린다던가 할 수 있겠죠. prop-types package는 이러한 상황에서 유용합니다. 잘못된 type의 prop이 전달되거나 전달되야할 prop이 전달되지 않으면 console을 통해 에러를 출력해줍니다.

app.jsx

  • name: PropTypes.string.isRequired
    Food Component에 전달될 name property는 string type이어야 하며 꼭 있어야 한다는 의미입니다. 꼭 필요하지 않다면 isRequired가 빠지면 됩니다.
  • rating: PropTypes.number.isRequired
    Food Component에 전달될 rating property는 number type이어야 하며 꼭 있어야 한다는 의미입니다.
import PropTypes from 'prop-types';

function Food({name, src, rating}){
	return (
      <div>
        <h2>I like {name}</h2>
        <img src={src} alt={name}>
        <span>{rating}</span>
      </div>
    )
}

Food.propTypes = {
  name: PropTypes.string.isRequired,
  src: PropTypes.string.isRequired,
  rating :PropTypes.number.isRequired
}
profile
누구나 실수 할 수 있다고 생각합니다. 다만 저는 같은 실수를 반복하는 사람이 되고 싶지 않습니다. 같은 실수를 반복하지 않기 위해 기록하여 기억합니다.🙃

0개의 댓글