Get a list of optional component details in reactions

Is there a way to get the keys for any propTypes referencing an optional property (i.e. not specified as mandatory)?

For example, given the following details:

 TestComponent.propTypes = { requiredProp: PropTypes.string.isRequired, optionalProp: PropTypes.func, optionalProp2: PropTypes.element } 

... I can get an array containing the elements: ["optionalProp", "optionalProp2"]

If there is no built-in way to do this, is there an elegant solution that:

  • Avoids hard-coding a list of them
  • Prevents getting a custom class using this functionality
  • It can be used in all of my reacting components.

I thought to use a context to define such a function, and then call it the current component as follows: this.context.getOptionalProps.call(this)

But this seems like a poor use of context.

+5
source share
1 answer

Update: the solution below only works for process.env.NODE_ENV !== 'production' with caution or not using

Not fully verified, but I managed to filter out the required firmware keys and get an array of additional details, for example:

  /** * Given a PropTypes Object returns an array of optional * prop keys. * * @param propTypes */ const optionalProps = propTypes => Object.keys(propTypes).filter(k => propTypes[k].isRequired); // console.log(optionalProps(TestComponent.PropTypes) output: // Array [ // "optionalProp", // "optionalProp2", // ] 

Then simply export it and import it for use wherever there is a React application.

+3
source

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


All Articles