Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of optional props of a component in reactjs

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:

  1. Avoids hard-coding a list of them
  2. Avoids deriving from a custom class with this functionality implemented
  3. Can be used throughout all my react components

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.

like image 364
sookie Avatar asked Oct 17 '22 04:10

sookie


1 Answers

Update: solution below only works for process.env.NODE_ENV !== 'production' use with caution or don't use

Not 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.

like image 59
jjjjjjjjjjjjjjjjjjjj Avatar answered Oct 21 '22 00:10

jjjjjjjjjjjjjjjjjjjj