How to define alternative required property in a React component PropTypes?
react-proptypes, reactjs
Solution
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:
data: PropTypes.array.isRequiredIf( props => !props.requestUrlSource ),
requestUrlSource: PropTypes.string.isRequiredIf( props => !props.data )
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.
Problem
This is the use case: A component `TableGroup` should require a user to specify `data` property which is an array of objects to be rendered in the table or `requestDataUrl` property from where the component will get that array of objects. In short, one of these two properties is required but not both. How could I achieve that in the following `component.propTypes` object? ``` TableGroup.propTypes = { fieldNames: React.PropTypes.array.isRequired, dataFields: React.PropTypes.array.isRequired, uniqueField: React.PropTypes.string.isRequired, data: React.PropTypes.array, requestUrlSource: http://someurl/api/resource } ```