Material-UI Autocomplete always show specified items

Viewed 564

Is there a way for an item in Material-UI's autocomplete to always show, regardless of whether or not has a match? For example under Shawshank Redemption below I've added an alwaysShow key pair. If I start typing "Pulp Fiction" I also want Shawshank Redemption to show.

import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function Playground() {
  const defaultProps = {
    options: top100Films,
    getOptionLabel: (option) => option.title
  };

  return (
    <div style={{ width: 300 }}>
      <Autocomplete
        {...defaultProps}
        renderInput={(params) => (
          <TextField {...params} label="movies" margin="normal" />
        )}
      />
    </div>
  );
}

const top100Films = [
  { title: "The Shawshank Redemption", year: 1994, alwaysShow: true },
  { title: "The Godfather", year: 1972 },
  { title: "12 Angry Men", year: 1957 },
  { title: "Pulp Fiction", year: 1994 },
  { title: "The Good, the Bad and the Ugly", year: 1966 },
  { title: "3 Idiots", year: 2009 },
];
1 Answers

You can use filterOptions prop in Autocomplete component. It gives you 2 parameter. First one is the options you've given to it and second one is the state of the input component. So you can customize it with your own filterize:

  const defaultProps = {
    options: top100Films,
    getOptionLabel: (option) => option.title,
    filterOptions: (options, state) => {
      let newOptions = [];
      options.forEach((element) => {
        if (element.title.includes(state.inputValue)) newOptions.push(element);
      });
      options.forEach((element) => {
        if (element.alwaysShow) newOptions.push(element);
      });
      return newOptions;
    }
  };

Edit suspicious-darwin-f99hs

Related