I need to make at least one of the props required:
MyComponent.propTypes = { data: PropTypes.object, url: PropTypes.string };
So in the example above, either data
or url
prop must be provided. The use case here is that the user could either provide the data
or the url
. If the url
is provided, then the component will fetch the data
.
Bonus question: How do I do at least one prop vs only one of the props?
I follow this rule of thumb: Three props is fine. Five props is a code smell. More than seven props is a disaster.
What are props in React? We use props in React to pass data from one component to another (from a parent component to a child component(s)). Props is just a shorter way of saying properties. They are useful when you want the flow of data in your app to be dynamic.
The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class.
PropTypes actually can take a custom function as an argument so you could do something like this:
MyComponent.propTypes = { data: (props, propName, componentName) => { if (!props.data && !props.url) { return new Error(`One of props 'data' or 'url' was not specified in '${componentName}'.`); } }, url: (props, propName, componentName) => { if (!props.data && !props.url) { return new Error(`One of props 'url' or 'data' was not specified in '${componentName}'.`); } } }
which allows for customer Error messaging. You can only return null or an Error when using this method
You can find more info on that here
https://facebook.github.io/react/docs/typechecking-with-proptypes.html#react.proptypes
from the react docs:
// You can also specify a custom validator. It should return an Error // object if the validation fails. Don't `console.warn` or throw, as this // won't work inside `oneOfType`. customProp: function(props, propName, componentName) { if (!/matchme/.test(props[propName])) { return new Error( 'Invalid prop `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.' ); } },
A more concise version of @finalfreq's solution:
const requiredPropsCheck = (props, propName, componentName) => { if (!props.data && !props.url) { return new Error(`One of 'data' or 'url' is required by '${componentName}' component.`) } } Markdown.propTypes = { data: requiredPropsCheck, url: requiredPropsCheck, }
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