propTypes in ReactJS

While working with small apps which have 5 to 6 components, it is easy to manage component, passing props. But as your app grows and has many components, it is very hard to manage.
It is good to have type checking while passing props, so that code becomes less error-prone.

PropTypes in ReactJS

ReactJS provides library 'prop-types' which can be used to check property types that are going to be passed to the component. You need to install prop-types library if it is not in your project.
Let us have an example.


import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';

const Greetings = (props) => {
  return(
    <div>
      Hello, {props.name}
      <br/>
      <br/>
      Your age is {props.age}.
    </div>
  );
};

// Component type doesn't matter. stateful or stateless
// componentName.propTypes
Greetings.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number
};

class Parent extends React.Component{
    render(){
        return (
            <div>
                <Greetings name="Learner" age={20} />
            </div>
        );
    }
}

ReactDOM.render(
    <Parent />,
    document.getElementById('root')
);
                    

Open above code in codepen.

In above code, to add propTypes just add Greetings.propTypes. property name is type of string and age is type of number. Remember, you need to use propTypes to assign type.

PropTypes List

There are many types that you can check using PropTypes. Let us have a look at the list. Now the list is not complete. We are just adding the ones which are used regularly.


AnyComponent.propTypes = {
    boolProp: PropTypes.bool,
    functionProp: PropTypes.func,
    objectProp: PropTypes.object,
    stringProp: PropTypes.string,
    numberProp: PropTypes.number,
    arrayProp: PropTypes.array,
    //React element
    elementProp: PropTypes.element,
    //Enum
    enumProp: PropTypes.oneOf(['one','two','three']),
    //Required of any type
    requiredAny: PropTypes.any.isRequired,
    // required of any particular type 
    requiredParticular: PropTypes.<any of above type>.isRequired
    // For example number req: PropTypes.number.isRequired
}
                    

Conclusion

In this section, we have learned about PropTypes of component in ReactJS.
In the next section, you will learn about difference between state and props ( state v/s props ) in ReactJS.