Pachu Pachu - 1 month ago 7
React JSX Question

React - proptypes validation - return Error doesnt work but throw does

So, Im looking at the react proptypes options, and I want to check if the children is a specific type, its really simple, and as mentioned here : https://facebook.github.io/react/docs/reusable-components.html#prop-validation I should return an Error object and not throw.
But when I return an Error object it doesn't print to the console, but if I throw an Error object everything works fine.

propTypes object:

const propTypes = {
children: function(props, propName) {
const children = props[propName];
React.Children.forEach(children, (child) => {
if (child.type !== Field) {
// doesnt work
return new Error('Error');
}
return;
});
}
};

const propTypes = {
children: function(props, propName) {
const children = props[propName];
React.Children.forEach(children, (child) => {
if (child.type !== Field) {
// does work
throw new Error('Error');
}
return;
});
}
};


What should I do?

Answer

Returning from forEach loop doesn't make enclosing function return. What you should better do is either use simple for loop or Array.prototype.some

const propTypes = {
  children: function(props, propName) {
    const children = props[propName];
    const invalid = React.Children.some(children, child => child.type !== Field);
    if (invalid) {
      return new Error('Error');
    }
  }
};
Comments