So, you have been working with react basics for a while now. And this post will take you through a bit of the advanced concept of ReactJS. Type Checking with PropTypes.

We use a lot of props in React. Today we will learn how to validate the datatype of those props. React Props Validation.

INSTALL AND IMPORT PROP-TYPES IN YOUR COMPONENT.

  1. Install prop-types package.

yarn add prop-types

OR

npm install prop-types

  1. Import prop-typesin your component.

import PropTypes from “prop-types”;

function Greeting(props) {

return(

<h1>Hello {props.name}</h1>

);

}

Greeting.propTypes = {

name: PropTypes.string

}

Here we imported the prop-types and used it to validate that the name which we are receiving as props should be of type string. If the name type is not string it will warn you in the browser console.

PROPTYPES VALIDATORS

PropTypes provide various validators to check our props from all different angles.

PROP TYPES

..

Greeting.propTypes = {

array: PropTypes.array,

boolean: PropTypes.bool,

function: PropTypes.func,

number: PropTypes.number,

string: PropTypes.string,

symbol: PropTypes.symbol,

}

Notice that for boolean its booland for function its func.

CHECK IF A PROP IS AN INSTANCE OF A CLASS.

Greeting.propTypes = {

greetMessage: PropTypes.instanceOf(Message),

}

IF A PROP COULD BE ONE OF MANY TYPES.

Greeting.propTypes = {

message: PropTypes.oneOfType([

PropTypes.string,

PropTypes.array,

])

}

IF YOU WANT TO VALIDATE AN ARRAY OF A SPECIFIC TYPE. LIKE AN ARRAY OF OBJECTS.

Greeting.propTypes = {

arrayOfObject: PropTypes.arrayOf(PropTypes.object)

}

IF YOUR PROP IS AN OBJECT AND YOU WANT TO VALIDATE ITS VALUES.

Greeting.propTypes = {

objectProp: PropTypes.shape({

color: PropTypes.string,

fontSize: PropTypes.number,

})

}

TO MAKE SURE THAT PROP IS PRESENT AND NOT EMPTY. JUST A CHAIN IS REQUIRED WITH ANY OF THE ABOVE EXAMPLES.

Greeting.propTypes = {

name: PropTypes.string.isRequired

}

DEFAULT PROPS

You can also set default props. If props are empty the default props will be used.

import PropTypes from “prop-types”;

 

function Greeting(props) {

return(

<h1>Hello {props.name}</h1>

);

}

Greeting.defaultProps = {

name: “Sam Smith”

}

If there is no name in props, Sam Smith will be used.

Soon I will update this post with Custom Validators. Till then, I hope you got something out of this post and Thank you for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *