Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autocomplete - How can I set a default value?

Tags:

material-ui

Does anyone know how to add a default value to the Autocomplete component? The component have a dataSource, and I'd like to load the page with a specific item already selected(e.g. fill the text field with the selected item's text and it's value already set).

Does anyone knows how? Big thanks for any help <3

like image 859
betoharres Avatar asked Mar 04 '17 19:03

betoharres


People also ask

How do I set default value in Autocomplete MUI?

If you need to set the initial value for your Autocomplete component and then never programmatically update it again, the best option is the defaultValue prop. This prop accepts a value that only gets rendered until an option is selected from the Autocomplete's dropdown list.

What is the default value of Append to option of Autocomplete () method?

By default its value is null. This option is used append an element to the menu. By default its value is null. When the value is null, the parents of the input field will be checked for a class of ui-front.

How do you get the selected value in Autocomplete material UI?

To get the value in the React Material-UI autocomplete, we can get the selected values from the onChange callback. We add the Autocomplete from the @material-ui/lab module. And we set the options prop to the top5films array to add the options for the autocomplete.


1 Answers

You can achieve this by setting the appropriate state in componentDidMount, for example:

componentDidMount() {
    // load your items into your autocomplete

    // set your default selected item
    this.setState({ allItems: [itemYouWantToSet], selectedItem: item.name, selectedItemId: item.id }
}

render() {
    return (
		<Autocomplete
		    value={this.state.selectedItem}
		    items={this.state.allItems}
		    getItemValue={(item) => item.name}
		    onSelect={(value, item) => {
		        this.setState({ selectedItem: value, selectedItemId: value, allItems: [item] });
		    }}
		/>
    )
}

Then your item is correctly selected from the list of available options when it loads.

like image 187
mscrivo Avatar answered Sep 27 '22 19:09

mscrivo