Validating Prop in React js
Posted By : Rajan Rawat | 04-Jul-2018
PropTypes will clear immediately when any user simply passed the faulty data in the prop. But
const { obj, arr } = React.PropTypes
Meeting.propTypes = {
info: obj.isRequired,
participants: arr.isRequired,
}
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.
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
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rajan Rawat
Rajan is a UI Developer, having good knowledge of HTML, CSS and javascript. His hobbies are internet surfing and watching sports.