facebook / prop-types

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

Conditional prop for value another prop #384

Closed camila-fran-gp closed 1 year ago

camila-fran-gp commented 1 year ago

I need to condition a prop of type oneOf according to the value of another prop, example:


Component.propTypes = {
  propA: PropTypes.oneOf(['op1','op2','op3','op4', ]),
  propB: (props) => {
    if (props.propA === 'op1') {
      return PropTypes.oneOf(['A1', 'A2', 'A3', 'A4'])
    }
    if (props.propA === 'op2') {
      return PropTypes.oneOf(['B1', 'B2', 'B3', 'B4', 'B5'])
    }
    if(props.propA !== 'op1' || props.propA !== 'op2'){
      return null //this prop should not exist
    }
  }
};

i tried with isRequiredIf but it doesn't work :/

ljharb commented 1 year ago

https://npmjs.com/airbnb-prop-types has this, so it should be possible. I’d suggest looking at the code.

ljharb commented 1 year ago

Specifically, you can’t return oneOf directly - you have to invoke it and return the result. Don’t forget to pass every argument that your custom propType received.