Appendix A: PropTypes {#appendix_prop_types}
PropTypes
are a way to validate the values that are passed in through a component's props
. Well-defined interfaces provide us with a layer of safety at the run time of our apps. They also provide a layer of documentation to the consumer of our components.
To use PropTypes
, install the package with npm
:
xxxxxxxxxx
$ npm i --save prop-types
And then import the library in whichever files you need it:
xxxxxxxxxx
import PropTypes from 'prop-types';
In versions of React earlier than
15.5.0
, you'd accessPropTypes
via the mainReact
library. This behavior is staged for deprecation.
We define PropTypes
by passing defining them as a static property of the component class. We can either do this by setting the propTypes
as a static property on the class or by setting them after the class is defined.
xxxxxxxxxx
class Component extends React.Component {
static propTypes = {
name: PropTypes.string
}
// ...
render() {
return (<div>{this.props.name}</div>)
}
}
We can also set the propTypes
as a static property on the component after the class is defined.
xxxxxxxxxx
class Component extends React.Component {
// ...
render() {
return (<div>{this.props.name}</div>)
}
// ...
Component.propTypes = {
name: PropTypes.string
}
createReactClass()
proptypes#When using the
createReactClass()
method to define a component, we pass thepropTypes
as a key with the value as the propTypes:
js const Component = createReactClass({ propTypes: { // propType definitions go here }, render: function() {} });
The key
of the propTypes
object defines the name of the prop we are validating, while the value is the types defined by the PropTypes
object (which we discuss below) or a custom one through a custom function.
The PropTypes
object exports a lot of validators that cover the most of the cases we'll encounter. For the not-so common cases, React allows us to define our own PropType
validators as well.
Validators#
The PropTypes
object contains a list of common validators (but we can also define our own. More on that later).
When a prop
is passed in with an invalid type or fails the prop type, a warning is passed into the JavaScript console. These warnings will only be shown in development mode, so if we accidentally deploy our app into production with an improper use of a component, our users won't see the warning.
This lesson preview is part of the Fullstack React course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Fullstack React, plus 0+ \newline books, guides and courses with the \newline Pro subscription.
