In lesson # 3, we learned about the properties (props) of React component, and in lesson # 9, we learned how to pass more than one property to these components. In this lesson, we will talk about property validation to reduce the time spent debugging applications.

How to Validate Props in React

Data handling within a DOM tree is quite beneficial as it takes away the burden from the app and increases the speed of rendering elements. There are a few techniques you can use when working with data in React components.

For the sake of simplicity, we create a functional component that takes 3 integer values as props and returns the result after adding these numbers.

Sounds easy? Right!

Maybe, it sounds easy but there is a little twist here.


JavaScript is a loosely typed scripting language, which means that you can initially set a variable as a string but if you pass a number or array, it won’t complain. Managing variable types can lead to extra time spent on debugging or adding comments.

Let’s say you have written a large number of React components and want to use one after some time. But do you what data type to use? Is it just string or array here?

You see, things are getting complex as you add more components. React provides a solution for this problem though.

React PropTypes

You need React PropTypes to declare the data type of the variable. Since React v15.5, React.PropType has moved into a separate npm package called prop-types library.

To use PropType you have to install it first using the command prompt. Cd to the root directory of your project and type npm install –save prop-types. Once you are done with the installation, it is ready to use.

Props Validation

You can validate props in two ways:

  1. Define PropTypes as an option to createClass()
    let component = React.createClass({
        propTypes: {
            //proptype definitions will go here. 
        },
        Render: function() {}
    })
  2. Create a component using ES6 class syntax and define propType as its method.
    class Component extends React.Component {
        render() {}
    }
    Component.propTypes = {
        //proptype definitions go here. 
    }

Example

Coming back to the code, we start from importing React and ReactDOM. The example simply adds 3 integers and prints the result.


Index.js

import React from 'react'
import ReactDOM from 'react-dom'

class Sum extends React.Component {

    render() {
        return (

            {
                a + b + c
            }
        )
    }
}
ReactDOM.render( < Sum a = '4' b = {3} c = {5} />, 
document.getElementById('root'))

As you can see, <Sum/> gets two integers and one string value. Instead of adding these numbers, React will render 435 on the screen and there is no error or warning message regarding the data type.

To correct this, we are going to use propTypes.

import React from 'react'
import ReactDOM from 'react-dom'
import { PropTypes } from 'prop-types';

class Sum extends React.Component {

    render() {
        return ( <div> {
                this.props.a + this.props.b + this.props.c
            }

                 </div>
        )
    }
}

Sum.propTypes = {
    a: PropTypes.number,
    b: PropTypes.number,
    c: PropTypes.number
}

ReactDOM.render( < Sum a = '4'b = {3} c = {5} />, 
document.getElementById('root'))

React will still display 435 but now there is a warning message in the console area.

React Error

To correct this, use:

ReactDOM.render(<Sum a={4} b={3} c={5}/>,

document.getElementById('root'))

React will display 12 now.

Here is another example of multiple data type validation.

Person.propTypes ={
name: PropTypes.string, 
gender: PropTypes.string, 
job:PropTypes:bool, 
email: PropTypes.string
}

Validating JS Object

React can also validate JavaScript objects. For example:

Person.propTypes = {
pet: PropTypes.shape({

name: PropTypes.string
gender:PropTypes.number
age:PropTypes.number

})
}

If you pass an object with age as a string, you will get a warning message.


Defining the valid range of Prop

You can also provide a list of accepted prop values.

For example:

Student.propTypes = {
status: PropTypes.oneOf(['pass', 'fail'])
}

If you pass unknown through the status prop, your browser will show a warning because it doesn’t comply with the options given.


Setting the prop value as mandatory

If you want the web browser to show a warning if you miss a prop value, use isRequired.

For example:

Employee.propTypes ={
employeeID: PropTypes.string.isRequired,
name:PropTypes.string.isRequired,
department: PropTypes.string,
salary: PropTypes.number
}

Default Props

To set the default prop values, use defaultProps.

For example:

Person.defaultProps ={nationality:'American'}

This will make sure that if someone skipped providing the nationality for Person component, the person will get the American nationality by default.

This completes our lesson on Props. You can also check the official page of PropsType mentioned above to get a complete list of available propTypes for React components. Try these examples, and if you have any question, feel free to leave it in the comment section below.

JSX in Depth Tutorial Home React Methods State and Life Cycle

 

Last modified: August 19, 2019

Comments

Write a Reply or Comment

Your email address will not be published.