goal
I have a multiple field that:
- we can select users present in the autocompletion (a list that I retrieve via API)
- We can enter the names of new users that we separate them with a comma
For that, I therefore need to retrieve the value of value and inputValue. For value, there is no problem but for inputValue, there is something that I do not understand
problem
When I modify the value of inputValue in onInputChange, its state is modified and reseted like that
information
I base on the example that material UI offers
Code
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
interface User {
id: number;
name: string;
}
const userList: User[] = [
{ id: 1, name: "name 1" },
{ id: 2, name: "name 2" },
{ id: 3, name: "name 3" }
];
export default function AutocompleteControlled() {
const [users, setUsers] = React.useState<number[]>([]);
const [inputValue, setInputValue] = React.useState("");
return (
<div>
<br />
<Autocomplete
multiple
value={userList.filter((el) => users.includes(el.id))}
onChange={(event: any, newValue: User[]) => {
setUsers(newValue.map((el) => el.id));
}}
inputValue={inputValue}
onInputChange={(event: any, newInputValue: string) => {
console.log("newInputValue", newInputValue);
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={userList}
getOptionLabel={(option) => option.name}
renderInput={(params) => (
<TextField {...params} label="Controllable" variant="outlined" />
)}
/>
</div>
);
}
All comments are welcome :)
