damio damio - 7 months ago 23
React JSX Question

React: Validate that no extra props has been passed

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 ?

Answer Source

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);
  }
});