Respond to redundant validation validation

In React, you can specify which details are required and what types they should have. Is it possible to display a validation warning when unknown prop names (e.g. unspecified in propTypes) are passed to the component?

+4
source share
1 answer

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
  }
});
+3
source

Source: https://habr.com/ru/post/1654164/


All Articles