PropTypes in React
-
Used for validating the types of props passed to a component. Used to help developers catch errors early in the development stages. Should be used before implementing functionality.
-
Installing. Use in development mode because it will have overhead depending on how much you use.
npm install --save-dev prop-types
- Using in component
import PropTypes from 'prop-types';
const Component = (props) => {
//Use props here
//Expecting a name(string) and number
}
//Will check if props contains name and number
//Also checks if those values match the data type
//If not matching then returns a warning in console
Component.propTypes = {
name: PropTypes.string.isRequired,
number: PropTypes.number.isRequired,
}