I am using MUI Select
in my React application where the user can select one of the option from the list. However, there is a requirement where a user can add a custom text in MUI Select
to create a new option.
Can anyone help how to achieve the same. Adding custom text in MUI Select
component.
It's not possible with Select
but you can do that using Autocomplete
component. Here is how:
options
listconst initialOptions = [
{ title: "The Shawshank Redemption" },
{ title: "The Godfather" },
{ title: "The Godfather: Part II" }
];
function App() {
const [inputValue, setInputValue] = React.useState("");
const [options, setOptions] = React.useState(initialOptions);
return (
<Autocomplete
options={options}
noOptionsText="Enter to create a new option"
getOptionLabel={(option) => option.title}
onInputChange={(e, newValue) => {
setInputValue(newValue);
}}
renderInput={(params) => (
<TextField
{...params}
label="Select"
variant="outlined"
onKeyDown={(e) => {
if (
e.key === "Enter" &&
options.findIndex((o) => o.title === inputValue) === -1
) {
setOptions((o) => o.concat({ title: inputValue }));
}
}}
/>
)}
/>
);
}
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.