Hello Friends 👋,

Welcome to Infinitbility.

MUI Autocomplete Provide option to show suggestion list in below Textfield and it works like a charm but problems comes when we want to show multiple options in suggestion like Name, and email.

When user select suggestion it should show only email in Textfield but it’s my expectation, it’s will show whole text available in option text.

So let’s comes to solution Material UI ( MUI ) Autocomplete provide onChange event and inputValue props to handle this types of situwation.

On onChange event we will only store email on our state and help of inputValue props we will show that on textfield value, let’s do with example.

import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function ComboBox() {
  const [selectedValue, SetSelectedValue] = useState("");

  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option) => `${option.name} -${option.email}`}
      onChange={(event, option) => {
        if (option?.email) {
          SetSelectedValue(option.email);
        } else {
          SetSelectedValue("");
        }
      }}
      inputValue={selectedValue}
      style={{ width: 300 }}
      renderInput={(params) => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { id: 1, name: "Infinit", email: "[email protected]" },
  { id: 2, name: "Bility", email: "[email protected]" }
];

In above example i’ve create a array of name, email option and both so on suggestion and when user will click on suggestion it only show email on textfield value.

Thanks for reading…