Jo Micheal
22 Dec 2021
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?
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
22 Dec 2021
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
2 Aug 2022
When i select multiple value that value, i want to display in another div.
© 2024 Copyrights reserved for web-brackets.com