sdc
sdc

Reputation: 3011

Is it possible to use Proptypes for an associative array of complex objects

Here is an example of the given structure I am looking for

const fields = {
  ["NAME"]: {isSet: false, display: "Customer Name", required: true},
  ["PHONE"]: {isSet: false, display: "Customer Phone", required: true},
  ["LOCATION_ID"]: {isSet: false, display: "Location ID", required: true},
  ["EMPLOYEE_ID"]: {isSet: false, display: "Employee ID", required: false},
  ["CUSTOMER_EMAIL"]: {isSet: false, display: "Customer Email", required: false},
  ["EMPLOYEE_EMAIL"]: {isSet: false, display: "Employee Email", required: false}
};

The key can be any string value and that value should be an object with isSet, display, required

Is this even possible or do I have to write a custom validator?

Header.propTypes = {
  fields: propTypes.arrayOf(propTypes.shape({
    ..... ?
  })).isRequired
};

Upvotes: 1

Views: 213

Answers (1)

SoKeT
SoKeT

Reputation: 610

First thing to note here is you can't use PropTypes.arrayOf since your structure is an object, not an array. You would need to use PropTypes.shape, but as you guessed, you can only do this with a custom validator.

If you check the source code for the shape validator, you'll see that it returns a function that loops over the keys of the object you pass it and runs the validator you passed along each key. Which is to say, you need to pass an object with explicit key names, which could be variables, but you can't give it a placeholder.

However, if your data structure was really an array, you could do the following:

Header.propTypes = {
    fields: PropTypes.arrayOf(PropTypes.shape({
        isSet: PropTypes.bool.isRequired,
        display: PropTypes.string.isRequired,
        required: PropTypes.bool.isRequired
    )).isRequired
}

Otherwise you're going to have to write a custom validator, which is a function that receives props, propName and componentName, and returns an Error object if the prop you're given doesn't satisfy the condition you want.

Upvotes: 1

Related Questions