1
votes

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.

1

1 Answers

1
votes

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

Edit 66749678/custom-text-in-mui-select-component