2

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?

1 Answer 1

1

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 theImageMultiCheck` component hence why I suggested using a ternary assignment operation on a variable.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @finalfreq, that explains it well. You are right in saying that I do not want to change the actual state of the label. So in my ImageMultiCheck I will just place a default-string in case the label-prop is missing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.