When I set the defaultValue in the react-select Component, it is correctly recognised and set, but is not highlighted in the select menu.
<Select onChange={handleChange} options={options} styles={styles} defaultValue={defaultValue} />
This is the defaultValue, and it’s correct:
{ "value": { "param_user": "TEST" }, "label": "TEST" }
Perhaps it is because the value is an object?
Does anyone have any suggestions?
Advertisement
Answer
You are correct, the problem arrises because the default implementation of react-select checks whether the option is selected by reference. This means that if your default option does not come from the options array itself, it will not display as selected. Fortunately, the react-select library allows you to pass in a predicate that determines whether an option is selected. In your case:
const isOptionSelected = (option, selectValue) => selectValue.some( (val) => val.value.param_user === option.value.param_user ); <Select isOptionSelected={isOptionSelected} onChange={handleChange} options={options} styles={styles} defaultValue={defaultValue} />