Getting the value in the React material-UI Autocomplete
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 /> )}/>
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>
Here is TS working example
const tags = ["perimeter", "Algebra", "equation", "square root"]; const handleInput = (e: React.SyntheticEvent, value: string[]) => { console.log(value); };<Autocomplete multiple options={tags} onChange={handleInput} renderTags={(value: readonly string[], getTagProps) => value.map((option: string, index: number) => ( <Chip variant="outlined" label={option} {...getTagProps({ index })} /> )) } renderInput={(params) => ( <TextField {...params} variant="filled" label="Tags" placeholder="select question tags" /> )} />
============ Output ===============