Validating Prop in React js

Posted By : Rajan Rawat | 04-Jul-2018

Reatjs has a PropTypes and they are used for catching the bug and validating the data types which are passed through prop. Reatjs props also used to set the flag prop and mandatory or set the default values. With less efforts they deliver good benefits

PropTypes will clear immediately when any user simply passed the faulty data in the prop. But unfortunately propTypes are the most utilized mechanisam in reactjs. You can the prop validation in any component like this 

const { obj, arr } = React.PropTypes
Meeting.propTypes = {
info: obj.isRequired,
participants: arr.isRequired,
}

This tools is not used for catching the bugs, but also used to documentation of a component like the way a component has to be used for passing a prop. Let's see a example of this

import React from 'react';
import PropTypes from 'prop-types';
const Person = (props) => 
 {props.firstName} {props.lastName}
  {props.country ? Country: {props.country} : null} Person.propTypes = { firstName:PropTypes.string, lastName:PropTypes.string, country:PropTypes.string }; export default Person;

Now we are clear with the idea of what to do and things need to pass. Object is needed with a property timestamp and two or more options like room and organizer. In any case the timestamp is missing, it will show immediately in the console

now you can see more with this example

const { shape, number, string, arrayOf } = React.PropTypes
Meeting.propTypes = {
  info: shape({
    timestamp: number.isRequired,
    room: number,
    organizer: shape({
      id: number.isRequired, 
      name: string,
    }),
  }).isRequired,
  participants: arrayOf(shape({
    id: number.isRequired, 
    name: string,
  })).isRequired,
}
        

Validation of data type

 as we have shown in the above example the React PropTypes is used for the validation of data type. This is the reason they are made.If i say i would use it for checking of basic data type.

  emp.propTypes = {
  email: PropTypes.string,
  phone: PropTypes.number,
  worksRemote: PropTypes.bool,
  updateCallback: PropTypes.func
}
        

now we can validate as what we want to. Though the more we understand , it becomes harder to understand our coding. It depends on the need how tightly we validate the prop. Usually we validate all the properties that you are using in the component and rest is shallow

 

About Author

Author Image
Rajan Rawat

Rajan is a UI Developer, having good knowledge of HTML, CSS and javascript. His hobbies are internet surfing and watching sports.

Request for Proposal

Name is required

Comment is required

Sending message..