Skip to content
Related Articles

Related Articles

Improve Article

ReactJS Typechecking With PropTypes – Set 1

  • Last Updated : 07 Apr, 2021

React allows us to pass arguments to a Component using something called props (stands for properties) which are passed to components via HTML attributes in the same way as arguments passed in a function. These give a way to pass data from one component to other components and render dynamic data in our render method. We can pass different types of data like integers, symbols, strings, arrays, objects, etc. as props to the components. We can either create defaultProps or can pass props directly as HTML attributes to the components or from outside a component and use them inside that component. You must be wondering can we check what type of values we are passing inside our Component through props? Yes we can use PropTypes for validating any data we are receiving from props. This is called Typechecking with Prop Types.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Required module: Before using PropTypes we will have to install it by typing the given command in the terminal.



npm install prop-types --save

Type-checking of the props is always performed during the rendering of a component because JavaScript is a typed language and data types are always determined at runtime.

var g = 20
// Changing the data type
g = "geeks"
g = [100,200]

For example, here g was declared as an integer initially. Then its type changes to a String then to an array. So in Javascript, a data type can be whatever we want it to be. As React is also written in Javascript there is no way to check props type before rendering (or runtime). That’s why React provided us propTypes to help us validate the data being received from props. Type-checking will warn us with a console message if we pass a type different from the data type specified by propTypes.

Let us see a how we can use propTypes for validation in both class components and functional components one by one:

Example 1: You can see in the below program that we are passing the prop named goodsPrice as a string in a class component and validating it as a number, even when everything is rendered perfectly on the browser. But our browser console has a warning message. This message clearly tells us that the prop named goodsPrice was expected to have a numeric value but instead a string value is passed.

index.js




import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'
  
// Component
class ClassComponent extends React.Component{
    render(){
        return(
          <div>
           {/* printing all props */}
           <h1>
           {this.props.goodsPrice}
           </h1>
          </div> 
       );
   }
}
   
// Validating prop types
ClassComponent.propTypes = {
  goodsPrice: PropTypes.number
}
   
// Creating default props
ClassComponent.defaultProps = {
  goodsPrice: "GeeksForGeeks"
}
   
ReactDOM.render(
    <ClassComponent  />, 
    document.getElementById("root")
);

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Example 2: You can see in the below program that we are passing the prop named goodsInfo as a number in a functional component but validating it as a string, even then everything is rendered perfectly on the browser. But our browser console has a warning message. This message clearly tells us that the prop named goodsInfo was expected to have a string value but instead a numeric value is passed.

App.js




import React from 'react'
import PropTypes from 'prop-types'
  
// Function
function ProfitComponent(props) {
  return (
      <div>
        {/* Printing the props */}
         <h1>
          {props.goodsInfo}
         </h1>  
      </div>
  )
}
  
// Creating default props
ProfitComponent.defaultProps = {
   goodsInfo: 10
}
  
// Validating prop types
ProfitComponent.propTypes = {
   goodsInfo: PropTypes.string
}
  
export default ProfitComponent;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Here’s a list of all the valid data types a prop can take in React:

  • PropTypes.array: Validates that the prop is an Array.
  • PropTypes.bool: Validates that the prop is a bool.
  • PropTypes.func: Validates that the prop is a function.
  • PropTypes.number: Validates that the prop is a number.
  • PropTypes.object: Validates that a prop is an Object.
  • PropTypes.string: Validates that the prop is a string.
  • PropTypes.symbol: Validates that the prop is a symbol.

Note: Not only data types, we can also validate React elements, specific value inside a data type or data that we are storing inside another data type (such as an array or an object). We will learn about this in detail in the next article ReactJS Typechecking With Props – Set 2.




My Personal Notes arrow_drop_up
Recommended Articles
Page :