Reputation: 4074
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...
Upvotes: 216
Views: 104551
Reputation: 4622
Wanted to note that nesting works beyond one level deep. This was useful for me when validating URL params:
propTypes = {
match: PropTypes.shape({
params: PropTypes.shape({
id: PropTypes.string.isRequired
})
})
};
Upvotes: 17
Reputation: 83
user: React.PropTypes.shap({
age: (props, propName) => {
if (!props[propName] > 0 && props[propName] > 100) {
return new Error(`${propName} must be betwen 1 and 99`)
}
return null
},
})
Upvotes: -6
Reputation: 10629
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
})
}
Upvotes: 412
Reputation: 62793
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.
// 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>
);
}
});
Upvotes: 14