Ilya Chernomordik
Ilya Chernomordik

Reputation: 30205

How to validate the class of a Prop and class of it's field (nested object) in React?

I have a class like this:

class ResponseState() {
   constructor(data) {
      this.data = data;
   }
}

Now I can validate that the prop is of this type:

Container.propTypes = {
   myProp: PropTypes.instanceOf(ResponseState).isRequired,
};

This works fine, but how can I validate the type of myProp.data as well? If I use PropTypes.shape, then I cannot check myProp itself.

There is a similar question here, but it does not quite give the answer to this exact problem.

Upvotes: 1

Views: 261

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

I'm surprised not to see any combining forms for PropTypes.

You could use a custom validator:

Container.propTypes = {
   myProp: function(props, propName, componentName) {
      if (!propName in props) {
         return new Error(propName + " is required");
      }
      const value = props[propName];
      if (!(value instanceof ResponseState)) {
         return new Error(propName + " must be an instance of ResponseState");
      }
      if (/*...validate value.data here ...*/) {
         return new Error(propName + " must have etc. etc.");
      }
   }
};

Upvotes: 1

Related Questions