Saturday, November 16, 2024
Google search engine
HomeLanguagesReactJS PropTypes

ReactJS PropTypes

In this article, we will learn about PropTypes in react and how we can use these PropTypes so that we can create strict rules for the data being passed in the props.

Issues with passing props

We passed different types of information like integers, strings, arrays, etc. as props to the components. We can either create defaultProps or have passed props directly as attributes to the components. We do not have a check on what type of values we are getting inside our Component through props.For larger Apps, it is always a good practice to validate the data we are getting through props. This will help in debugging and also helps in avoiding bugs in the future. Let us see how to do this.

React propTypes

Before the release of React 15.5.0 version propTypes was available in the react package but in later versions of React have to add a dependency in your project. You can add the dependency to your project by using the command given below:

npm i prop-types

We can use the propType for validating any data we are receiving from props. But before using it we will have to import it. Add the below line at the top of your index.js file : 

import PropTypes from 'prop-types';

Once we have imported propTypes we are ready to work with them. Just like defaultProps, propTypes are also objects where keys are the prop names and values are their types.

Syntax:

ComponentClassName.propTypes{
    
    propName1 : PropTypes.string,
    propName2 : PropTypes.bool,
    propName3 : PropTypes.array,
    .
    .
    propNamen : PropTypes.anyOtherType
}

In the above Syntax, the ComponentClassName is the name of the class of Component, anyOtherType can be any type that we are allowed to pass as props. For the props which do not validate the type of data specified by propTypes, a warning on the console will occur.

Let us see a complete program that uses propTypes for validation for a better understanding: 

Example: Write the following code in index.js file of your react application 

javascript




import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom/client';
  
// Component
class ComponentExample extends React.Component{
    render(){
        return(
                <div>
                  
                    {/* printing all props */}
                    <h1>
                        {this.props.arrayProp}
                        <br />
  
                        {this.props.stringProp}
                        <br />
  
                        {this.props.numberProp}
                        <br />
  
                        {this.props.boolProp}
                        <br />
                    </h1>
                </div>
            );
    }
}
  
// Validating prop types
ComponentExample.propTypes = {
    arrayProp: PropTypes.array,
    stringProp: PropTypes.string,
    numberProp: PropTypes.number,
    boolProp: PropTypes.bool,
}
  
// Creating default props
ComponentExample.defaultProps = {
  
    arrayProp: ['Ram', 'Shyam', 'Raghav'],
    stringProp: "neveropen",
    numberProp: "10",
    boolProp: true,
}
  
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <ComponentExample />
  </React.StrictMode>
);


Output:gfg

Explanation:

You can see in the above program that we are passing the prop named numberProp as a string but validating it as a number. Still, everything is rendered perfectly on the browser but our browser console has a warning message. This message clearly tells us that the prop named numberProp was expected to contain a numeric value but instead, a string value is passed.

Note: In recent versions of React the React.PropTypes is moved to a different package, and we will have to install that package separately in order to use it. Please go to https://www.npmjs.com/package/prop-types link for installation instructions.

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