简体   繁体   中英

Custom text in MUI Select component

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:

  • 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

编辑 66749678/custom-text-in-mui-select-component

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM