Master Type Checking in React with Package Proptypes

Proptypes are javascript packages that can be used as standalone or with other Javascript Libraries such as React JS. Package Prototypes allows us to do type checking for properties that are to be passed within a component.

If the property passed does not match the declared proptype then an error is shown in the console.

Prototypes come with a lot of options and type checking attributes which you can use in your own way. Apart from this, you can create your custom own prop function to do type checking if you have any additional validation to be done or else for most of the part of your project the attributes provided by PropTypes are sufficient.

The Package PropTypes are different from form validation packages as they only type checks the property passed to a component.

Why you should use PropTypes

When your app grows you have less control over the type of data you are passing to the component as in most cases you will not encounter an error message. But the behavior of the application changes.

So using the PropType will detect these issues in the development stage.

Watch Video

Installing PropTypes

Type npm i prop-types to install package and below code to include it into your code file.

import propTypes from 'prop-types'

Note

Initially, it was React.PropTypes and from version 15.5. It has moved propTypes into a different package.

Here starting with the App component, for example to type check prop name and age

import propTypes from 'prop-types'

function App( props ) {
    return (
        <>
            <div>Name: {props.name}</div>
            <div>Age: {props.age}</div> 
        </>
    );
}

App.propTypes = {
    name : propTypes.string.isRequired, // marks the name as mandatory to be passed every time
    age : propTypes.number 
}

<App name={"Rajeev"} age={12} />

Pass an object to App.propTypes and in that objects types are specified. The prop name must always be passed to App the component as isRequired an attribute is specified.
There are multiple of propTypes available such as propTypes.string, propTypes.number, propTypes.object, propTypes.func, propTypes.array and propTypes.symbols.

Prop types with default props values

App.defaultProps = {
    name : "Lohit",
    age : 18 
}

The defaultProps contains initial values of the props. App.propTypes are executed after the defaultProps.

ProTypes with Array

App.propTypes = {
    users : propTypes.array
}  

Only prop with datatype array can be pass to prop users.

Proptypes for Objects

App.propTypes = {
    user : propTypes.object,
    order_count : propTypes.objectOf( propTypes.number ),
}   

Use .object attribute to type check for objects and for a specific type of object use .objectOf( ) method.

If your prop may be one of the types then use oneOfType() method.

App.propTypes = {
    age : propTypes.oneOfType( [
        propTypes.string,
        propTypes.number
    ] ),
}

You can also do a type check within the object’s keys.

App.propTypes = {
    user : propTypes.shape({
        name : propTypes.string.isRequired,
        age : propTypes.number.isRequired,
        dob : propTypes.objectOf(Date).isRequired,
    }).isRequired
}

Type checking prop for component or HTML node.

App.propTypes = {
    component : propTypes.element // react component
    node : propTypes.node // html node
}

Check if a prop is a function

App.propTypes = {
    onSubmit : propType.func
}

The propType.func will check where the passed prop is a function.

Create custom propType Function

If your requirements are different then you can pass a function and do conditional validation and if any error then return Error object.

App.propTypes = {
    name : propTypes.string.isRequired,
    age : propTypes.number.isRequired,
    onSubmit : propTypes.func.isRequired,
    qty : function( props, name ){
            if( props.qty < 2 ){
                return new Error(  
                    "cannot have qty less than 2"
                )
            }
        }
    }

Final Words

I consider PropTypes as one of the most useful packages for React JS. However, you can only type check the props that are passed to components. Need to explicitly specify the variables to be type-checked.

If you completely want to avoid these types of errors then I recommend you to go for TypeScript which is statically typed and provides all Javascript features.