Reputation: 147
I'm currently working with the Material-UI "Autocomplete" component to have multi-select capability.
https://codesandbox.io/s/material-demo-9zlfz?file=/chipdemo.js
/* eslint-disable no-use-before-define */
import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
export default function ComboBox() {
const handleOnChange = ({ target }) => console.log(target.value);
const [state, setState] = useState([]);
return (
<Autocomplete
multiple
id="combo-box-demo"
options={top100Films}
value={state}
onChange={(e, newval) => {
console.log(newval);
setState(prev => [...prev, newval[newval.length - 1]]);
}}
getOptionLabel={option => option.title}
style={{ width: 300 }}
renderInput={params => (
<TextField
{...params}
label="Combo box"
variant="outlined"
fullWidth
onChange={handleOnChange}
/>
)}
/>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
...
];
I'm attempting to utilize it as a controlled component, I'm able to add as many chips as I'd like from the list, however when it comes to removing them individually, I have two different cases
If the autocomplete has 1 chip (length of 0) and I click the x, I'm served with
TypeError
Cannot read property 'title' of undefined
If the autocomplete has > 1 chip and I click the x, It will instead add the last chip over and over again.
Looking at the autocomplete API (https://material-ui.com/api/autocomplete/) I dont see any "onClose" for the chips themselves, only for the popup with the options within.
Is there a specific prop I need to remove items from a controlled Autocomplete?
Thank you for any thoughts, greatly appreciated!
Upvotes: 0
Views: 2096
Reputation: 496
you need to change your onchange to this:
onChange={(e, newval) => {
console.log(newval);
setState(newval);
}}
Upvotes: 1