Typechecking with PropTypes in ReactJS

Typechecking is a feature which catches a range of validations and make sure the data you have received is valid. Incase an invalid value is provided for a prop, then a warning message is shown in JavaScript console.

For performance reasons, props type checked only in development mode.

In order to use type checking of props in React, you should have installed a package named: prop-types

To install please use the below command

npm install prop-types

To run type checking on the props for a component, you can assign the special propTypes property.

import propTypes from "prop-types";

Tutorial.propTypes = {
	tutorial_name: PropTypes.string
};

Example:

optionalArray:PropTypes.array,
optionalBool:PropTypes.bool,
optionalFunc:PropTypes.func,
optionalNumber:PropTypes.number,
optionalObject:PropTypes.object,
optionalString:PropTypes.string,
optionalSymbol:PropTypes.symbol,

Example of props string type type-checking

Tutorial.js

import React, {Component} from "react";
import Pt from "prop-types";

//Class component...
class Tutorial extends React.Component{
    render(){
        return(
            <div>
                <h1>Welcome to {this.props.tutorial_name}</h1>
                <h2>I am learning {this.props.tutorial_name} from {this.props.tutorial_site}.</h2>
            </div>
        );
    }
}

Tutorial.propTypes = {
    name:Pt.string
};

export default Tutorial;

index.js

import React from "react";
import ReactDOM from "react-dom";

import Tutorial from "./Tutorial";

ReactDOM.render(<Tutorial tutorial_name="ReactJS" tutorial_site="Share Query" />, document.getElementById("root"));

Trending Topics