It's not possible with Select but you can do that using Autocomplete component. Here is how:
- Take control of the input value and the options
- Detect if the user pressed Enter and add the new option in the
options list
Example
const 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 }));
}
}}
/>
)}
/>
);
}
Live Demo
