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.
The autocomplete is a normal text input enhanced by a panel of suggested options.
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.
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>
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 /> )} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With