Is there a way to get the keys for any propTypes
that reference an optional property (i.e are not specified as being required)?
For example, given the following props:
TestComponent.propTypes = {
requiredProp: PropTypes.string.isRequired,
optionalProp: PropTypes.func,
optionalProp2: PropTypes.element
}
...can I get an array that contains the items: ["optionalProp", "optionalProp2"]
If there's no built-in way to do this, is there an elegant solution that:
I was thinking of using the context to define such a function, and then call it on the current component like so: this.context.getOptionalProps.call(this)
But it seems like a bad use of the context.
process.env.NODE_ENV !== 'production'
use with caution or don't useNot thoroughly tested, but I managed to filter out the prop keys that are required, and get an array of optional props like this:
/**
* 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 just export it and import for use wherever in your React application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With