I used to write components with multiple configuration For example:
ResponsiveTable.PropTypes = {
width: React.PropTypes.number, //used if widthOffset and minWidth are undefined
widthOffset: React.PropTypes.number, //used if width is undefined
minWidth: React.PropTypes.number, //used if width is undefined
};
How can I declare props that can be used only if there i snot already other props set?
A XOR option would be usefull. I read https://facebook.github.io/react/docs/reusable-components.html but it didn't help.
Any ideas?
PropTypes is React’s internal mechanism for adding type checking to components. React components use a special property named propTypes to set up type checking. When props are passed to a React component, they are checked against the type definitions configured in the propTypes property.
React components use a special property named propTypes to setup type-checking. When props are passed to a React component, they are checked against the type definitions configured in the propTypes property. When an invalid value is passed for a prop, a warning is displayed on the JavaScript console.
When an invalid value is passed for a prop, a warning is displayed on the JavaScript console. If default props are set for the React component, the values are first resolved before type checking against propTypes. Therefore, default values are also subject to the prop type definitions.
import PropType from ‘prop-types’; we can use it on any type of component (Stateful or stateless). At the end of component before exporting it we write it as − Player.propTypes= {}; Note the propType on name of component as shown above.
Solution:
React.PropTypes.oneOfType([
React.PropTypes.shape({
width: React.PropTypes.number.isRequired
}),
React.PropTypes.shape({
widthOffset: React.PropTypes.number,
minWidth: React.PropTypes.number.isRequired
}),
])
you can create custom property:
yourComponent.propTypes = {
...
customProp: function(props, propName, componentName) {
if(checkValid){
return new Error('validation failed');
}
}
...
}
this is in react docs https://reactjs.org/docs/typechecking-with-proptypes.html
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