Home > database >  Autocomplete Search Via Another Paramter
Autocomplete Search Via Another Paramter

Time:05-17

In below example , -

https://codesandbox.io/s/g5ucdj?file=/demo.tsx

I want to achieve functionality such that , If I have array -

const top100Films = [
  { title: 'The Shawshank Redemption', year: 1994 },
  { title: 'The Godfather', year: 1972 },
  { title: 'The Godfather: Part II', year: 1994 },]

Then , in autocomplete when I search via year , I should get label options for title. Eg. If I enter year 1994 in search box , I should get two title options for selection -

The Shawshank Redemption
The Godfather: Part II

I tried changing option -

options={top100Films.map((option) => option.year)}

But through this I get year as a option which I want title as a option , having year entered in text box.

CodePudding user response:

As I see you are using React js, so I will suggest you, to use React-select for better functionality

  1. Add Package using "npm i --save react-select".
  2. Import as a Component
  3. use <Select {data}/> in jsx format
  4. Add json data to {data}.

Reference documantion: React-select npm https://react-select.com/home

Everything is perfectly documented

CodePudding user response:

You can use MUI createFilterOptions

import { createFilterOptions } from '@mui/material/Autocomplete';

Declare filterOptions

const filterOptions = createFilterOptions({
  matchFrom: 'any',
  stringify: (option) => option.year.toString(),  //.toString because year is integer
});

Then in you Autocomplete tag add this:

filterOptions={filterOptions}

Codesandbox example.

The code is in javascript, you can change to typescript accordingly. For typescript follow this link

  • Related