Reputation: 5506
I have used Material UI's auto complete component to create a searchable select input. I pass it options which is an array of strings of all possible options.
<Grid item xs = {props.xs} className = {classes.formItem}>
<Autocomplete
multiple
options = {props.options}
disableCloseOnSelect
getOptionLabel = {( option ) => option}
renderOption = {( option, {selected} ) => (
<React.Fragment>
<Checkbox
icon = {icon}
checkedIcon = {checkedIcon}
style = {{ marginRight: 8 }}
checked = {selected}
onChange = {props.onChange( option, selected )}
/>
{option}
</React.Fragment>
)}
renderInput = {( params ) => (
<TextField {...params} variant = "outlined" label = {props.label} />
)}
/>
</Grid>
Sometimes I would like to fetch the options from an api which have been previously selected. However when I pass this list of options to the component it does not show in the UI which options have been selected already. As can be seen bellow depending on my 'edit' prop I initialise the component's selected options as either an empty array or an array of the previously selected options
const [collaborators, setCollaborators] = React.useState( props.edit ? currentProject.collaborators : [] )
Anyone have any ideas why the UI does not display the selected options?
Thanks
Upvotes: 0
Views: 5416
Reputation: 5506
Hi if anyone has this trouble, I solved it by reading the docs properly, the autocomplete component contains a defaultValue props which can be passed an array of the options you would like to show as selected from the start.
Upvotes: 3