Hello hello StackOverflow. Today I have a burning problem that needs an answer.
So I've been trying to make this work for the past week now, to no avail.
So the issue I am facing is I am trying to make an autocomplete using MUI's autocomplete component, but I want it to act a little different.
I want it to show auto complete options, and when you click them it insteads doesn't use the label value but instead the id value. But I also want it to be able to accept manual input aswell. So for example copying in stuff, or just writing it in instead of picking an autocomplete option.
This is what i've tried so far in terms of code:
const [callNumber, setCallNumber] = useState("")
const updateCallNumber = (_event: React.SyntheticEvent<Element, Event>, value: any) => {
console.log(value.number)
setCallNumber(value.number)
}
<Autocomplete
id="free-solo-demo"
freeSolo
onChange={updateCallNumber}
value={callNumber}
options={contactsData}
getOptionLabel={(option) => option.name}
isOptionEqualToValue={(option, value) => option.name === value.name}
renderInput={(params) => <TextField
{...params}
label="Number"
variant="standard"
InputProps={{
...params.InputProps,
startAdornment: (
<>
<InputAdornment position="start">
<CallIcon />
</InputAdornment>
{params.InputProps.startAdornment}
</>
)
}}
/>
}
/>
PS contactsData is an array that consists of ID, Name, Number
Thanks for reading, and kind regards
Klaus.
You need to use the inputValue (property of Autocomplete) to display the value you want and keep the onChange and the value.
I code an sample that you can try:
import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
export const friends = [
{ value: "Etienne", inputProps: "toto" },
{ value: "Deborah", inputProps: "tata" },
{ value: "Geneviève", inputProps: "titi" },
];
const initialState = { value: "", inputProps: "" };
export default function ControllableStates() {
const [selected, setSelected] = useState(initialState);
const getFirendsValue = () => {
return friends.map((friend) => friend.value);
};
const getFriendSelecter = (value) => {
return friends.filter((item) => item.value === value);
};
const handleChange = (newValue) => {
if (newValue === null) {
return setSelected(initialState);
}
const newState = getFriendSelecter(newValue);
return setSelected(...newState);
};
return (
<>
<Autocomplete
disablePortal
id="demo"
options={getFirendsValue()}
value={selected.value}
inputValue={selected.inputProps}
sx={{ width: 300 }}
onChange={(e, newValue) => handleChange(newValue)}
renderInput={(params) => (
<TextField {...params} label="Recommandé par" />
)}
/>
</>
);
}
Say me if it's good for you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.