Reputation: 1517
I have this component which can cater single-select or multiselect feature. If multiselect is true, the initialValue should be an empty array. Else, it should be an empty object. Setting defaultProps looks a little complicated with this scenario. Is there any way I can set default prop of initialValue
depending on the value of multiselect
?
const wrap = compose(
setPropTypes({
initialValue: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
multiselect: PropTypes.bool,
}),
defaultProps({
initialValue: // [] or {} or ((otherProps) => otherProps.multiselect ? [] : {}) ??? , if there is such thing
multiselect: false,
})
);
If I set it as {}
, the user could still pass multiselect={true}
without passing defaultValue. In this case, several functions will map
through defaultValue whereas it's not an array, resulting to improper handling of data plus numerous errors.
The same would happen if I just carelessly assume other scenarios. Is there any perfect approach for this? Thanks in advance.
Upvotes: 1
Views: 1156
Reputation: 673
In plain language, it is not possible. I had the same dilema in a few components of mine. My suggest is to use two properties, one per each select type. Besides, you can remove the multiselect property and check it watching which of the two properties I mentioned is not null. In short:
const wrap = compose(
setPropTypes({
initialSingleValue: PropTypes.object,
initialMultiValue: PropTypes.array,
}),
defaultProps({
initialSingleValue: {}
initialMultiValue: nil,
})
);
I hope this helps you.
Upvotes: 1