Reputation: 6301
I'm using propTypes
with React because I like how it warn me when I pass something dumb. But sometimes I misspell my prop or I forget to put it in my propTypes
and it never get validated.
Is there a (standard) way to make React also validate that no extra props have been passed ?
Upvotes: 3
Views: 500
Reputation: 26336
This will do as you ask.
componentDidMount() {
let matchPropTypes = Object.keys(this.constructor.propTypes).every((a, index) => a === Object.keys(this.props)[index])
if (!matchPropTypes) {console.log('propTypes do not match props', Object.keys(this.constructor.propTypes), Object.keys(this.props))}
}
Upvotes: 1
Reputation: 29989
I'm not sure whether there's a standard way, but you can certainly do a quick and dirty check using Object.keys
.
var propsCount = Object.keys(this.props).length,
propTypesCount = Object.keys(this.propTypes).length;
if(propsCount === propTypesCount) {
// correct number of props have been passed
}
The only edge case you will have to watch for is props.children
, as this arrives as an implicit property if you nest components/HTML inside your component.
If you want a more fine grained approach, then you'll have to pick out the keys and iterate them yourself, checking.
var passedPropNames = new Set(Object.keys(this.props)),
expectedPropNames = new Set(Object.keys(this.propTypes));
passedPropNames.forEach(function(propName) {
if(!expectedPropNames.has(propName)) {
console.warn('Not expecting a property called', propName);
}
});
expectedPropNames.forEach(function(propName) {
if(!passPropNames.has(propName)) {
console.warn('Expected a property called', propName);
}
});
Upvotes: 2