Appendix A: PropTypes {#appendix_prop_types}

Table of Contents

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:

And then import the library in whichever files you need it:

In versions of React earlier than 15.5.0, you'd access PropTypes via the main React 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.

We can also set the propTypes as a static property on the component after the class is defined.

createReactClass() proptypes#

When using the createReactClass() method to define a component, we pass the propTypes 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.

Unlock This Course

Get unlimited access to Fullstack React, plus 0+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course Fullstack React