-
이 글은 React의 PropTypes라이브러리 사용에 관한 내용을 정리하기 위해 작성하였습니다.< propTypes >
propTypes are a mechanism to ensure that components use the right type of props, and receive the right type of props.
< propTypes are useful for two reasons >
1. prop validation : ensure that your props are doing what they're supposed to be doing.
2. documenting props : makes it easier to glance at a file and quickly understand the component class inside.
< Apply PropTypes >
- First, To use PropTypes, import 'prop-types' library.
import PropTypes from 'prop-types';
- Second, declare propTypes for your component after the component has been defined.
: message, trueFalse, technology are expected prop.class Example extends React.Component { // ~~~ } Example.propTypes = { message: PropTypes.string.isRequired, trueFalse: PropTypes.bool, tetchnology: PropTypes.func }
: propTypes !== PropTypes
propTypes is Example's property name, PropTypes is library name that we use.
< PropTypes in Function Components >
To write propTypes for a function component, you define a propTypes object as a property of the function component itself.
Example)
const Example = (props) => { return <h1>{props.message}</h1>; } Example.propTypes = { message: PropTypes.string.isRequired };
'React' 카테고리의 다른 글
Style (0) 2021.12.06 The Effect Hook (0) 2021.12.06 The State Hook (0) 2021.12.06 Function Components (0) 2021.12.05 Component Lifecycle (0) 2021.12.02 - First, To use PropTypes, import 'prop-types' library.