Reputation: 1428
In React I can set default PropTypes like so:
MyComponent.defaultProps = {
multiple: false
}
Now, one of my Props is an associative array. I want to set the default value for one of the key value pars, for example:
ImageMultiCheck.defaultProps = {
multiple: false,
myArray: {label: 'default Value'}
}
This is not working. Maybe its just a syntax mistake. How can I do that?
Upvotes: 2
Views: 2562
Reputation: 6980
Default props is only used if no props are passed in for that specific property. If you are passing in a prop of myArray
but the object has no key/value pair for label
then you would have two options:
You could handle that case in the parent component and do a check to see if label exists on the object being passed down and if not add the default. Otherwise in your ImageMultiCheck
component you would have to do some sort of var label = myArray.label ? myArray.label : 'default value'
Since it is a prop you don't want to mutate your myArray
object by doing something like myArray.label = 'default value' in the
ImageMultiCheck` component hence why I suggested using a ternary assignment operation on a variable.
Upvotes: 1