Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare React PropTypes XOR

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?

like image 763
Damien Leroux Avatar asked Mar 09 '16 12:03

Damien Leroux


People also ask

What is proptypes in react?

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.

How do you check props in React React?

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.

What happens if a prop type is invalid in react?

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.

How do I import a prop type from a component?

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.


2 Answers

Solution:

React.PropTypes.oneOfType([
    React.PropTypes.shape({
        width: React.PropTypes.number.isRequired
    }),
    React.PropTypes.shape({
        widthOffset: React.PropTypes.number,
        minWidth: React.PropTypes.number.isRequired
    }),  
])
like image 152
Damien Leroux Avatar answered Oct 18 '22 02:10

Damien Leroux


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

like image 1
Krzysztof Sztompka Avatar answered Oct 18 '22 02:10

Krzysztof Sztompka