Autocomplete - How to set the default value?

Does anyone know how to add a default value for an Autocomplete component? The component has a dataSource , and I would like to load a page with a specific selected item (for example, fill a text box with the text of the selected item and an already set value).

Does anyone know how? Thanks so much for any help <3

+6
source share
5 answers

You can use the searchText property.

 <AutoComplete searchText="example" ... /> 
0
source

Try it...

 componentWillReceiveProps(nextProps) { let value = nextProps.value if (value) { this.setState({ value: value }) } } 
0
source

Name your component like that

 <SelectCountryAutosuggest searchText="My Default Value" /> 

Make sure you apply the default value to the class loading state

 class SelectCountryAutosuggest extends React.Component { state = { value: this.props.searchText, //apply default value instead of '' suggestions: [], }; ... } 
0
source

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 will be correctly selected from the list of available options at boot.

0
source

Have you tried setting the dynamic searchText prop dynamically? You can pass the value that you want to set for the Autocomplete component as searchText prop. Sort of,

 <Autocomplete searchText={this.state.input.name} // usually value={this.state.input.name} /> 

By default, it will have the initial value set in the TextField of the Autocomplete component, but when the user makes any changes, it calls the autocomplete options depending on the dataSource prop.

-1
source

Source: https://habr.com/ru/post/1265031/


All Articles