By declaring a propTypes object for a component, I can specify the expected props and their types for a given component. This is helpful for future maintainers of our code and provides helpful warnings when props are incorrectly entered or missing.
To take advantage of prop validation, first import the PropTypes module from React:
import { PropTypes } from 'react';
Then, in our component, we give it a static property of propTypes:
class Example extends Component {
static propTypes = {
foo: PropTypes.string.isRequired,
bar: PropTypes.func,
baz: PropTypes.number.isRequired
}
}
In the preceding example, foo and baz are the required props for the Example component. foo is expected to be a string, while baz is expected to be a number. bar, on the other hand, is expected to be a function but is not a required prop.