JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

React Tutorial - Props Validation

Author:JIYIK Last Updated:2025/03/15 Views:

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

How to validate Props? It's actually very simple. React provides us with PropTypes for validation. When the data we pass to Props is invalid (that is, the data type passed to Props does not match the validated data type), a warning message will be issued in the console.

See the following example

var Propsva = React.createClass({
    propTypes: {
        optionalArray: React.PropTypes.array,
        optionalBool: React.PropTypes.bool,
        optionalFunc: React.PropTypes.func,
        optionalNumber: React.PropTypes.number,
        optionalObject: React.PropTypes.object,
        optionalString: React.PropTypes.string,
    },
    getDefaultProps:function(){
        return {
            optionalArray: ['onmpw.com','——track memory blog'],
            optionalBool: true,
            optionalFunc: function (arg) {
                console.log(arg);
            },
            optionalNumber: 3,
            optionalObject: {
                object1: "objectvalue1",
                object2: "objectvalue2",
                object3: "objectvalue3",
            },
            optionalString: "My Onmpw",
        };
    },
    render:function(){
        return (
            <div>
                <h3>Array:{this.props.optionalArray}</h3>
                <h3>Bool:{this.props.optionalBool}</h3>
                <h3 onClick={this.props.optionalFunc}>Func:click</h3>
                <h3>Number:{this.props.optionalNumber}</h3>
                <h3>Object:{this.props.optionalObject.object1}</h3>
                <h3>Object:{this.props.optionalObject.object2}</h3>
                <h3>Object:{this.props.optionalObject.object3}</h3>
                <h3>String:{this.props.optionalString}</h3>
            </div>
        );
    }
});
ReactDOM.render(
    <Propsva />,
    document.getElementById('content')
);

Of course, there is nothing wrong with the above example. Let's modify the above example

getDefaultProps:function(){
    return {
        optionalArray: 'onmpw.com——Memory Blog',
        optionalBool: true,
        optionalFunc: function (arg) {
            console.log(arg);
        },
        optionalNumber: 3,
        optionalObject: {
            object1: "objectvalue1",
            object2: "objectvalue2",
            object3: "objectvalue3",
        },
        optionalString: "My Onmpw",
    };
},

Then, we will find the following warning in the console

Warning: Failed propType: Invalid prop `optionalArray` of type `string` supplied to `Propsva`, expected `array`.

This is one case, verifying the data type of Props. Another case is to verify whether Props has a value. See the following code

propTypes: {
    optionalArray: React.PropTypes.array.isRequired,
    optionalBool: React.PropTypes.bool.isRequired,
    optionalFunc: React.PropTypes.func,
    optionalNumber: React.PropTypes.number,
    optionalObject: React.PropTypes.object,
    optionalString: React.PropTypes.string,
},

Add isRequired after React.PropTypes.array and React.PropTypes.bool to indicate that optionalArray and optionalBool must have values.

getDefaultProps:function(){
    return {
        optionalFunc: function (arg) {
            console.log(arg);
        },
        optionalNumber: 3,
        optionalObject: {
            object1: "objectvalue1",
            object2: "objectvalue2",
            object3: "objectvalue3",
        },
        optionalString: "My Onmpw",
    };
},

In the above code, we remove optionalArray and optionalBool, and then run the code in the browser, and you will find the following error in the console:

Warning: Failed propType: Required prop `optionalArray` was not specified in `Propsva`.
Warning: Failed propType: Required prop `optionalBool` was not specified in `Propsva`.

Of course, the above are just two simple cases. There are many other things and forms of verification for Props. For details, we can refer to the official React documentation .

Here we have a knowledge point that needs to be explained, which is getDefaultProps. This is the default assignment of Props. See the following code

var ComponentDefaultProps = React.createClass({
    getDefaultProps: function() {
        return {
            value: 'Default Value'
        };
    },
    render:function(){
        return (
            <div>{this.props.value}</div>
        )
    }
});
ReactDOM.render(
    <ComponentDefaultProps />,
    document.getElementById('content')
);

getDefaultProps() can ensure that when the parent component does not pass in Props, the current component can be guaranteed to have the default Props value. It should be noted that the return result of getDefaultProps will be cached. Therefore, we can use Props directly without having to manually write some meaningless repetitive code.

This is the end of the introduction to Props verification. I hope this article will be helpful to you.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Validating phone numbers in PHP

Publish Date:2025/04/12 Views:180 Category:PHP

PHP has two ways to validate phone numbers, one is regular expression regex and the other is filter the method. We can use to regex set a template and validate the phone number based on that template, but filter will only exclude the unwant

Validating Email in PHP

Publish Date:2025/04/12 Views:120 Category:PHP

We will introduce a method to validate email addresses in PHP using filter_var() the function and FILTER_VALIDATE_EMAIL filter name ID. filter_var() The function takes an email as the first parameter and a filter name FILTER_VALIDATE_EMAIL

Redis password verification command AUTH

Publish Date:2025/04/09 Views:78 Category:Redis

Redis has not made much optimization in terms of security, but has made great efforts in terms of performance and ease of use. A very simple security method for Redis is password verification, which requires the use of the AUTH command. Let

Validating inserted values in MySQL table with duplicate key

Publish Date:2025/04/09 Views:98 Category:MySQL

Traditional SQL INSERT statements do not perform input validation of their parameters/values ​​against existing database tables, which sometimes results in errors when duplicate keys are found during the insert process. This is handled

Git authentication

Publish Date:2025/03/28 Views:163 Category:Git

This article demonstrates connecting a local repository to a remote repository on GitHub/Gitlab without getting 身份验证失败 error messages. Creating a local repository from scratch in Git To create a local repository from scratch, fo

How to avoid cross-origin (CORS) issues in React/Next.js

Publish Date:2025/03/17 Views:170 Category:NETWORK

In this article, we will introduce how to avoid cross-origin (CORS) issues in React/Next.js. Cross-origin resource sharing (CORS) is a protocol that defines how web requests should be handled when crossing different URLs.

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:188 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:187 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial