React
prop-types -정의,사용 예제
Judith Hopps
2022. 9. 13. 11:59
반응형
prop-types란??
컴포넌트가 전달받은 props가 정말 내가 원하는 값인지 확인해준다.
props의 인자의 특징을 미리 기술해 잘못 사용될 경우를 예방한다.
prop-types사용 예제
App.js(Food 컴포넌트가 쓰여진 파일)에 아래 내용을 추가해준다.
Food.propTypes = {
name: PropTypes.string.isRequired,
picture : PropTypes.string.isRequired,
rating : PropTypes.string.isRequired
};
후에 실행하면 console창에 아래와 같은 에러창이 뜬다.

Warning: Failed prop type: Invalid prop `rating` of type `number` supplied to `Food`, expected `string`
즉, rating이라는 타입이 prop type에는 string으로 되어 있으나 num형식으로 되어있다는 것이다.
이를 아래와 같이 수정해주면 콘솔창에 에러는 사라진다.
Food.propTypes = {
name: PropTypes.string.isRequired,
picture : PropTypes.string.isRequired,
rating : PropTypes.number.isRequired
};
이처럼 propType에 형식을 지정해주면
키 값의 설정이 올바른지 확인할 수 있다.
더욱 자세한 설명은 아래 링크에 들어가서 볼 수 있다.
https://github.com/facebook/prop-types
GitHub - facebook/prop-types: Runtime type checking for React props and similar objects
Runtime type checking for React props and similar objects - GitHub - facebook/prop-types: Runtime type checking for React props and similar objects
github.com
반응형