user image

Jo Micheal
Published in : 2021-12-22

How to get the selected object in "Autocomplete material ui"?

React js

How to get the selected value & object in the autocomplete component in Reactjs Material UI? I can get the value but I need to get the entire option object because there are some options I add to each option, I am using this way to get the selected value when the user click on the option 

<Autocomplete filterOptions={filterOptions} options={this.state.dropdown} groupBy={(option) => option.type} getOptionLabel={(option) => option.name || ''} renderOption={(option) => ( <React.Fragment> {option.name} </React.Fragment> )} // closeIcon= { () => { return; } } renderInput={(params) => ( <TextField {...params} placeholder="What are you looking for?" value={values.search} label="" name=search /> )} onInputChange={(e, value) => { setFieldValue('search', value); }}/>

I am using onInputChange but it gets the final label of the option, 

like when i click on Wheels, i get wheel but the object of the option should look like 

{ type: 'Cars', parentCat: 32, rule: 'subcategory', name: 'Wheels'}

so How can I get this option?

Comments

Mohamed Atef Date : 2021-12-22

Best answers

51

Best answers

51

Hi Jo, you can get the object using onChange 

onChange={ (e, obj) => { console.log(obj); setFieldValue('search', obj); } }

that's how it suppose to work,
here is the full code 

<Autocomplete filterOptions={filterOptions} options={this.state.dropdown} groupBy={(option) => option.type} getOptionLabel={(option) => option.name || ''} renderOption={(option) => ( <React.Fragment> {option.name} </React.Fragment> )} // closeIcon= { () => { return; } } renderInput={(params) => ( <TextField {...params} placeholder="What are you looking for?" value={values.search} label="" name=search /> )} // onInputChange={(e, value) => { setFieldValue('search', value); }} onChange={ (e, obj) => { console.log(obj); setFieldValue('search', obj); } }/>

Good luck

Jo Micheal Date : 2021-12-22

Thanks this works for me, i tried to use getOptionSelected but i realized that it's being used to select a specific option in the list on change not to get the selected option

JAY SINGH Date : 2022-08-02

When i select multiple value that value, i want to display in another div.

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

[Solved] Cannot read properties of null (reading 'getBoundingClientRect')
Publish date: 2021-12-02 | Comments: 2

Tag: React js

React Redux : Connect is not called
Publish date: 2022-03-02 | Comments: 1

Tag: React js

Warning: React.jsx: type is invalid
Publish date: 2022-05-06 | Comments: 1

Tag: React js