stateNPAValue[formData.state.vale] = 0: "All",1: "959", 2: "203",3: "860", 4: "475" // API response for NPA data
const [selectedNamesState, setSelectedNamesState] = useState([]);
const transformedNpaData = stateNPAValue[formData.state.value].map((label, index) => ({
label,
value: index.toString() // You can use the index as the value or any unique identifier
}));
<Autocomplete
multiple
id="fixed-tags-demo"
name="Npa"
value={selectedNamesState}
onChange={(event, newValue) => {
setSelectedNamesState(newValue)
NPAHandler(newValue);
changeHandleStateErrorRemove(event)
}}
options={transformedNpaData}
getOptionLabel={(option) => option.label.replace(/[[]']+/g, '')}
defaultValue={[transformedNpaData[0].label]}
renderTags={(tagValue, getTagProps) =>
tagValue.map((option, index) => (
<Chip
label={option.label.replace(/[[]']+/g, '')}
{...getTagProps({ index })}
/>
))
}
style={{ width: 500 }}
renderInput={(params) => <TextField {...params} label={formData.state.value} />}
isOptionEqualToValue={(option, value) => {
return option.value === value.value;
}}
/>
I wanted to select "All" as a default value in multiselect dropdown but defaultValue option is not working. Please let me know what is wrong with this code.
2
Answers
looks like your
Autocomplete
component and your props are expecting the data type to be like below, and you are giving a correct type tooptions
prop. I thinkdefaultValue
should also be the same typeso I think changing the default value as below will solve the issue.
You are rendering Autocomplete using controlled input. In such cases, you will have to set the default value in the useState that is controlling the selected values for Autocomplete. Read the doc here. This is what its written in doc:
Considering that the option
All
will always be on the top of the list. You can initialize selectedNamesState as follows:Your options array in array of object, in case you are comfortable with converting it into array of string then the solution can be even simpler.