What is the correct way to validate route props in React class?
I tried:
route: React.PropTypes.object
- my eslint complains: Prop type
object
is forbidden react/forbid-prop-types route: React.PropTypes.instanceOf(React.propTypes)
- this results in a
warning at runtime: Right-hand side of 'instanceof' is not callable Check the render method of bla
We have the policy to validate props enforced by eslint rules, how can I validate route object?
My code:
var bla = React.createClass({
displayName: 'bla',
propTypes: {
route: React.PropTypes.object,
})
class RootRoute extends React.Component {
render() {
return (
<Router history={hashHistory}>
<Route path="/" component={bla}/>
</Router>
);
}
}
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 is used for props validation. If some of the props aren't using the correct type that we assigned, we will get a console warning. After we specify validation patterns, we will set App. defaultProps.
A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.
For you first try, use PropTypes.shape
.
Read the eslint docs for more info about the rule: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md
Read react-router docs for information about the shape of route
object: https://github.com/reactjs/react-router/blob/master/docs/API.md#proptypes
For your second try, inside instanceOf()
, you need to put a type or a class. I am not sure where you getting this React.propTypes
. A typo?
Read more about PropTypes.instanceOf
here: https://facebook.github.io/react/docs/reusable-components.html
you can also use.
PropTypes.objectOf(PropTypes.any).isRequired
You want to ensure that the route
prop in your component is an instanceof
ReactRouter.Route
.
You can use the PropTypes.instanceOf
function to accomplish this.
var MyComponent = React.createClass({
displayName: 'MyComponent',
propTypes: {
route: React.PropTypes.instanceOf(Route).isRequired
}
});
And the router component just as you had it.
var RootRoute = React.createClass({
render() {
return (
<Router history={hashHistory}>
<Route path="/" component={MyComponent}/>
</Router>
);
}
})
Incidentally, you should try not to mix class ... extends ...
syntax with the createClass
syntax for creating new components.
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