React PropTypes

Learn via video courses
Topics Covered

Overview

React proptypes is an important mechanism by which we can check if the passed prop is of valid data type or not. PropTypes allow you to specify what type of props you are expecting in a certain component. Since javascript has no built-in type-checking feature, so we have to use react proptypes to validate props.

Introduction To React Proptype

Proptypes, as the name, suggests - property types. It is used to check the type of property passed to our react component and save us from the bugs in apps that are very hard to find and remove. Proptypes export a large variety of validators (which helps to check the type). for example - Proptypes.string, Proptypes.array, etc. Don't worry we will see the implementation of this further, for now just try to understand the meaning and usage of proptypes in react.

How To Use React Proptypes?

For using proptypes in react, we have to use a package called "prop-types".

Including Prop-types Package In Your React App.

  1. Go to your console and type -> npm install --save prop-types. (This will install the prop-types package in your app.)
  2. Import prop-types in the starting of your code, using ->
    import PropTypes from 'prop-types;' (for ES6)
    var PropTypes = require('prop-types'); (for ES5)

Now we successfully included prop-types package for react in our app. Now let's see about its usage.

Using Proptypes In React

1. Creating a basic react app with a component and some props to it.

Suppose we run a bakery and we print the current order using react on our webpage. The code for the same is as follows :

[App.js]

[OrderDetails.js]

As you can see in [app.js] we are calling component OrderDetails with two props. Let's say there is an offer going on and we have decided to give 5 additional pie with the order. So, in [OrderDetails.js] we are returning a String that has information about our current order. We used {order_quantity + offer} for calculating the total number of pie there.

error due to wrong proptype

However, it can be seen easily from the above output of this app, that there is an error in calculating orders as we order_quantity is 2 and offer is 2. we should get total pie as {2 + 5} i.e. 7. But we are getting 25.

This error happened because we passed order_quantity as "2" (String), not as a number, But as we are not using react proptype, our app is unable to identify the error and returned the total as "25" instead of 7.

This type of error can be soo painful to identify and remove in large projects that's why we should use react proptypes. Now let's see how to implement proptypes in react.

2) Implementing Proptype

As we can see in the above code we specified Proptypes to our properties passed in the component.

Now if we try to pass String in place on the number for order_quantity, we get an warning :

warning message for using wrong proptype

It says that order_quantity is of type number, we cannot pass String. So let's pass the number and see what is the correct output.

[App.js]

output when correct proptype is passed

Now, we get our correct output 7 by passing order_quantity in right proptype . This is one of the most useful applications of react proptypes.

Now we know what are proptypes in react and how to use them. So let's move further and see different types of react proptypes.

Basic Types of PropTypes

There are many types of react proptypes, but here we will go through some basic ones which are also primitive types in javascript such as string, number, objects, etc.

TypeClassExample
StringPropType.string“Learning react proptypes”
NumberPropType.number7
ObjectPropType.object{name: “Rohit”}
BooleanPropType.booltrue/false
SymbolPropType.symbolSymbol(“m”)
FunctionPropType.funcconst say = {console.log(“React Proptype”)}

we can chain any above proptype with isRequired, which will make it compulsory to pass the corresponding property in our component.

Collective Type

Apart from basic types of proptypes in react, there are also exists collective types such as arrays and collective object types.

(A) Array Types

Here are some arrays type proptypes in react :

TypeClassExample
ArrayPropTypes.array[]
Array of numbersPropTypes.arrayOf([type])[9,3,5,2,7]
Array of stringPropTypes.oneOf([arr])["Proptypes" , "react"]
Array of objectsPropTypes.oneOfType([types])PropTypes.instanceOf(Title)

(B) Object Types

Similar to array types, there are also some collective object types as follows :

TypeClassExample
ObjectPropTypes.object{Topic : “Proptypes in react”}
Object ShapePropTypes.shape(){item : PropTypes.string , cost : PropTypes.number}
Number ObjectPropTypes.objectOf(){cost : 2500 }
InstancePropTypes.objectOf()new Fruit("Apple")

Advance Type Checking

Apart from checking the basic type, we can also check component type using react proptypes.

(A) How To Check For A React Component

If we want to check if a prop is a react component or not, we can use the PropTypes.element. Let's see how to do it with an example.

(B) How To Check For A React Component Name

In react, we can also pass react component as a prop. So if we want to check whether a prop has a name of react component then we can use PropTypes.elementType .

Here we have passed Component as a prop MainComponent. To check that the pass prop has a name of react component, we can do :

Custom Types

In addition to basic proptypes checking, we can also do custom validation to props according to our needs. Let's take a better understanding of it with an example.

Suppose we want to display a fruit name in our react component, but in addition to it we also want that fruit must be one of these: ["Apple" , "Mango" , "Banana"] , so we can do it with help of custom validators.

In the above component Fruit we have passed fruit prop as "Orange".

In the above react proptype of a Fruit component, we have passed a validator that returns an error when the passed fruit is not one of desired ones. For example, in the case of orange, we will get a warning as :

custom validation of proptype

Requiring Single Child

React proptypes can also be used to check that a single child can be passed to a component as children.

Default Prop Values

In our react components, sometimes we want to pass a default value in a prop. First, let's understand what is the default value of a prop. A default value of a prop is that value that will be used when the prop value is not passed.

As in this Icecream example, we are not passing any flavor prop.

[Calling Component] <Icecream /> [Icecream Component]

As no flavor prop is passed in Icecream, so a default prop will be passed to our component i.e flavor: "Vanilla".

Function Components

If we are using functional components in our react code. Then we can use react proptypes in our component directly as :

Conclusion

In this article, we have learned about :

  • React proptypes and how we can use them in our react app.
  • we have also gone through the use and necessity of prop-types in react.
  • Basic types of react proptypes such as string, number etc.
  • Advanced types such as array types and object types.
  • We have seen how to check for a react component using proptypes.
  • custom validation of props.
  • we have seen how to require single child
  • Default proptypes are also discussed along with their use.
  • we have learned how to improve react components by type checking of props and also prevent errors that may arise due to props.