In React you can specify which one props are required and which types they should have. Is there possibility to display validation warning when unknown prop names (for example unspecified in propTypes) are passed to component?
1 Answers
3
votes
With a higher-order component anything is possible:
// This is not a full solution, merely a sketch of one way to do it
const OnlyValidProps = WrappedComponent => {
return class extends React.Component {
render() {
const actualProps = Object.keys(this.props);
const expectedProps = Object.keys(WrappedComponent.propTypes);
const hasPropMisMatch = (
actualProps.length != expectedProps.length ||
!actualProps.every(key => expectedProps.contains(key))
);
if (hasPropMisMatch) {
console.warn(`Props mismatch! expected: ${expectedProps} actual: ${actualProps}`);
}
return <WrappedComponent {...this.props} />;
}
};
}
// Usage
OnlyValidProps(class MyClass extends React.Component {
static propTypes = {
x: React.PropTypes.number,
y: React.PropTypes.number
}
});