Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the value in the React material-UI Autocomplete

I am referring to the documentation of React Material-UI (https://material-ui.com/components/autocomplete/).

In the demo code,

    <Autocomplete       options={top100Films}       getOptionLabel={(option: FilmOptionType) => option.title}       style={{ width: 300 }}       renderInput={params => (         <TextField {...params} label="Combo box" variant="outlined" fullWidth />       )}     /> 

I get how it works, but I am not sure how I am supposed to get the selected value.

For example, I want to use the onChange prop to this so that I can make some actions based on the selection.

I tried adding onChange={v => console.log(v)}

but the v does not show anything related to the selected value.

like image 549
Dawn17 Avatar asked Nov 01 '19 21:11

Dawn17


People also ask

What is material UI autocomplete?

The autocomplete is a normal text input enhanced by a panel of suggested options.

How do you write autocomplete in React?

To create an autocomplete component in React, use the react-autocomplete library. The react-autocomplete module provides properties, methods, and events that can trigger an ajax request on typing, which will fetch the list items and render them inside the render menu.


2 Answers

The onChange prop works for multiple autocomplete values as well (@Steve Angello @ShwetaJ). The value returned is a list of all the selected options.

const [selectedOptions, setSelectedOptions] = useState([]);  const handleChange = (event, value) => setSelectedOptions(value);  const handleSubmit = () => console.log(selectedOptions);  . . .  <Autocomplete   multiple   autoHighlight   id="tags-outlined"   options={top100Films}   getOptionLabel={(option) => option.title}   onChange={handleChange}   filterSelectedOptions   renderInput={(params) => (     <TextField       {...params}       variant="standard"     />   )} />  . . .   <button onClick={handleSubmit}>Submit!</button> 
like image 41
bcbl001 Avatar answered Oct 14 '22 08:10

bcbl001


Solved by using passing in the (event, value) to the onChange props.

<Autocomplete     onChange={(event, value) => console.log(value)} // prints the selected value     renderInput={params => (         <TextField {...params} label="Label" variant="outlined" fullWidth />     )} /> 
like image 90
Dawn17 Avatar answered Oct 14 '22 06:10

Dawn17