facebook / prop-types

Runtime type checking for React props and similar objects
MIT License
4.48k stars 356 forks source link

Conditional PropTypes #186

Closed lifeiscontent closed 4 years ago

lifeiscontent commented 6 years ago

is there a way to say, if I have propA, propB is required?

ljharb commented 6 years ago

Use requiredBy from https://github.com/airbnb/prop-types

lifeiscontent commented 6 years ago

@ljharb is there a way to say one of 2 props are required with this package?

e.g. aria-labelledby or aria-label

ljharb commented 6 years ago

@lifeiscontent use or and combine it with two requiredBys.

dryoma commented 4 years ago

Why was this closed, I wonder? Seems like a feature that is natural for the package and shouldn't require third party libs.

lifeiscontent commented 4 years ago

@dryoma i realized a custom validator is pretty easy to create

joshuapinter commented 4 years ago

Use isRequiredIf.

There is a PR from 4 years ago by @evcohen that added isRequiredIf to the PropTypes library. Unfortunately, even at that time they were putting the PropTypes library in maintenance mode and would not merge it in.

The company I work for still uses PropTypes and so we forked the master branch of the PropTypes library and added this functionality in.

So now you can do something like this:

propB: PropTypes.string.isRequiredIf( props => props.propA )

Super clean and minimal.

Feel free to use our fork in your own project by updating your package.json with the following:

"prop-types": "github:cntral/prop-types#isRequiredIf"

NOTE: It does not take a boolean param, only a function that is passed the props and needs to return a boolean.

ljharb commented 4 years ago

@joshuapinter airbnb-prop-types may also be helpful.