React

propTypes

WebDevLee 2021. 12. 7. 01:07

이 글은 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.
    class Example extends React.Component {
    	// ~~~
    }
    
    Example.propTypes = {
      message: PropTypes.string.isRequired,
      trueFalse: PropTypes.bool,
      tetchnology: PropTypes.func
    }
    : message, trueFalse, technology are expected prop.
    : 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
};