Thursday, December 5, 2024
Google search engine
HomeLanguagesReactJS Typechecking With PropTypes – Set 3

ReactJS Typechecking With PropTypes – Set 3

In the previous article ReactJS Typechecking With PropTypes – Set 2, we discussed instance validation, single and multiple data types validation, types and shapes validation, and exact validation in props. In this article, we will discuss about pass anything validation, required validation, and custom validation of props.

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

Example 1: Passing any data type inside props 

We can validate prop of any data type, whether it is a number, string, symbol, array, object, etc using this method. It means we can pass any valid data type as props inside a component.

App.js




import React, { Component } from 'react'
import PropTypes from 'prop-types'
  
// Component
class ProfitComponent extends Component {
  render() {
   return (
      <div>
        {/* Printing the props */}
         <h1>
          {this.props.goodsNo}
         </h1>
         <h1>
          {this.props.goodsInfo}
         </h1>
      </div>
      )
  }
}
  
// Creating default props
ProfitComponent.defaultProps = {
   goodsNo: 67,
   goodsInfo: "GeeksForGeeks"
}
  
// Validating prop types
ProfitComponent.propTypes = {
   goodsNo: PropTypes.any,
   goodsInfo: PropTypes.any
}
  
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:

Explanation: You can see in the above program that we are passing the prop named goodsNo as a number and goodsInfo as a string in a class component and validating both of them as any data type. Everything gets rendered perfectly on the browser and no warning message appears. This clearly tells us that any value can be passed inside props named goodsNo and goodsInfo, whether it is a string, number, array, or an object, etc.

Example 2: Required Validation for data passed inside props

We can validate that a prop is provided or not. To do that, we use isRequired to make sure that a warning message is shown if the prop isn’t provided or if its data type is different from the specified one.

App.js




import React, { Component } from 'react'
import PropTypes from 'prop-types'
  
// Component
class ProfitComponent extends Component {
  render() {
   return (
      <div>
        {/* Printing the props */}
         <h1>
          {this.props.goodsNo}
         </h1>
      </div>
      )
  }
}
  
// Creating default props
ProfitComponent.defaultProps = {
   goodsNo: "GeeksForGeeks"
}
  
// Validating prop types
ProfitComponent.propTypes = {
   goodsNo: PropTypes.number.isRequired
}
  
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:
 

Explanation: You can see in the above program that we are passing the prop named goodsNo as a string and require it strictly as a number in our props. Still, everything gets rendered perfectly on the browser but a warning message appears in the console. This clearly tells us that our prop named goodsNo was strictly requiring a value of number but is passed as a string. So, we conclude that isRequired method is just another way of validating the data passed inside a prop.

Example 3: Making our own prop validation function or Custom Validation

We can also specify our own custom validation or a prop validation function to check what data must be passed as props inside our component. It returns an Error object as a warning message if the validation fails.

App.js




import React, { Component } from 'react'
  
// Component
class ProfitComponent extends Component {
  render() {
   return (
      <div>
        {/* Printing the props */}
         <h1>
          {this.props.goodsNo}
         </h1>
      </div>
      )
  }
}
  
// Creating default props
ProfitComponent.defaultProps = {
   goodsNo: 20
}
  
// Validating prop types
ProfitComponent.propTypes = {
   goodsNo(props, propName, component){
     if(props[propName] < 100){
        return new Error(`${propName} is smaller than 100`)
     }
   }
}
  
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:

Explanation: You can see in the above program that we are passing the prop named goodsNo as a number with the value of 20 and validating if its value is greater than 100 or not in our own validation function. It is also called a custom validation function whose name must be the same as our propName (goodsNo in this case). We provide the following parameters in our function goodsNo():

  • props: It refers to all the props that we are passing inside the component.
  • propName: It refers to the prop for which we are creating this validation function, which in this case is goodsNo.
  • component: It refers to the component in which we are passing our props, which in this case is our class component ProfitComponent.

We access our propName goodsNo by writing props[propName] in the function and validate if its value is greater than 100 or not. As our props value is 20, we get an Error message provided by us in the console of our browser. It clearly tells us that the value of our prop named goodsNo is smaller than 100. This way, we can validate the data passed into a prop with a user-defined validation function.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments