Oleksandr Fomin
Oleksandr Fomin

Reputation: 2356

Search by name or ID with Material UI autocomplete

I'm building a search modal with autocomplete and what I eventually want to achieve is to be able to search people by their names OR ID. But as you choose a person from suggestion and the name goes to input field I don't want the ID to show up (the reason is real IDs will be really long and it would look ugly). Here is a screenshot for better understanding of the issue enter image description here

I don't want that number 6 to appear once I choose an option from suggestions.

Here is my code for the autocomplete

 <Autocomplete
        multiple
        id="tags-outlined"
        options={students}
        onInputChange={(event) => event.target}
        getOptionLabel={({ firstName, lastName, id }) =>
          `${firstName} ${lastName} ${id}`
        }
        filterSelectedOptions
        renderOption={({ firstName, lastName, id }) => {
          return (
            <div>
              <div>
                {`${firstName} `}
                {lastName}
              </div>
              <span>{id}</span>
            </div>
          );
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            className={classes.input}
            variant="outlined"
            label="Name or Student ID"
          />
        )}
      />

Upvotes: 6

Views: 6587

Answers (1)

bertdida
bertdida

Reputation: 5288

You can use createFilterOptions to create your custom filter and pass that as filterOptions prop to Autocomplete.

In your case, you have to provide a stringify config, this config controls how an option is converted into a string so that it can be matched against the input text fragment — docs.

...
import Autocomplete, { createFilterOptions } from "@material-ui/lab/Autocomplete";

const filterOptions = createFilterOptions({
  stringify: ({ firstName, lastName, id }) => `${firstName} ${lastName} ${id}`
});

function App() {
  return (
    <div>
      <Autocomplete
        multiple
        id="tags-outlined"
        options={students}
        onInputChange={(event) => event.target}
        filterOptions={filterOptions}
        getOptionLabel={({ firstName, lastName }) => {
          // this is how our option will be displayed when selected
          // remove the `id` here
          return `${firstName} ${lastName}`;
        }}
        filterSelectedOptions
        renderOption={({ firstName, lastName, id }) => {
          return (
            <div>
              <div>
                {`${firstName} `}
                {lastName}
              </div>
              <span>{id}</span>
            </div>
          );
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            variant="outlined"
            label="Name or Student ID"
          />
        )}
      />
    </div>
  );
}

Edit heuristic-clarke-moz4d

Upvotes: 9

Related Questions