I'm using a data object as my props for a component in ReactJS.
<Field data={data} />
I know its easy to validate the PropTypes object itself:
propTypes: { data: React.PropTypes.object }
But what if I want to validate the values inside? ie. data.id, data.title?
props[propName]: React.PropTypes.number.required // etc...
propTypes = { //// key is the name of the prop and // value is the PropType } export default Count; PropTypes are also objects with a key and a value pair where the 'key' is the name of the prop while the value represents the type or class by which they are defined.
PropTypes is React's internal mechanism for adding type checking to components. React components use a special property named propTypes to set up type checking. When props are passed to a React component, they are checked against the type definitions configured in the propTypes property.
React JS has an inbuilt feature for validating props data type to make sure that values passed through props are valid. React components have a property called propTypes which is used to setup data type validation. Syntax: The syntax to use propTypes is shown below. class Component extends React.
PropTypes are a way to validate the values that are passed in through our props. node We can pass anything that can be rendered, such as numbers, string, DOM elements, arrays, or fragments that contain them using the React.
You can use React.PropTypes.shape
to validate properties:
propTypes: { data: React.PropTypes.shape({ id: React.PropTypes.number.isRequired, title: React.PropTypes.string }) }
Update
As @Chris pointed out in comments, as of React version 15.5.0 React.PropTypes
has moved to package prop-types
.
import PropTypes from 'prop-types'; propTypes: { data: PropTypes.shape({ id: PropTypes.number.isRequired, title: PropTypes.string }) }
More info
If React.PropTypes.shape
doesn't give you the level of type checking you want, have a look at tcomb-react.
It provides a toPropTypes()
function which lets you validate a schema defined with the tcomb library by making use of React's support for defining custom propTypes
validators, running validations using tcomb-validation.
Basic example from its docs:
// define the component props var MyProps = struct({ foo: Num, bar: subtype(Str, function (s) { return s.length <= 3; }, 'Bar') }); // a simple component var MyComponent = React.createClass({ propTypes: toPropTypes(MyProps), // <--- ! render: function () { return ( <div> <div>Foo is: {this.props.foo}</div> <div>Bar is: {this.props.bar}</div> </div> ); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With