Don P
Don P

Reputation: 63667

Can you specify that at least one prop of a set must be provided?

In React propTypes, is it possible to specify that one prop or another prop must be provided?

For example, if myPropA is not provided, then you must provide myPropB.

Docs don't appear to have a method for this.

Upvotes: 0

Views: 365

Answers (2)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38807

You can specify an optional prop type for myPropA, then provide a custom validation prop function for myPropB. You can supply any custom error message you would want in whatever structure you need. You can use the function arguments such as the prop name and component name to build this message. This example also uses only the property names myPropA/myPropB instead of introducing aan additional custom property key/name.

import React from 'react';
import PropTypes from 'prop-types';

const Hello = ({ name, myPropA, myPropB }) => <h1>Hello {name}!</h1>;

Hello.propTypes = {
  myPropA: PropTypes.string,
  myPropB: function(props, propName, componentName) {
    // required validation
    if(!props.myPropA && !props.myPropB) {
      return new Error(`Failed prop type: The prop '${propName}' is required in '${componentName}' when prop 'myPropA' is 'undefined', but it's value is '${props[propName]}'.`);
    }

    // string validation
    if(!props.myPropA && props.myPropB && typeof props.myPropB !== 'string') {
      return new Error(`Failed prop type: Invalid prop ${propName} of type '${typeof props[propName]}' supplied to ${componentName}, expected 'string'.`);
    }
  },
};

export default Hello;

Here is an example in action.

Hopefully that helps!

Upvotes: 1

BorisS
BorisS

Reputation: 3193

Yes, there is a way. You can add your own custom validation function.

const propTypes = {
    customProp: function(props, propName, componentName) {
      if ( !("myPropA" in props) && !("myPropB" in props) ) {
        return new Error(
        "Invalid prop"
      );
    }
  }
}

JSFiddle: Link

Upvotes: 0

Related Questions