Home > OS >  How to get the ID on the searched data autocomplete material UI react
How to get the ID on the searched data autocomplete material UI react

Time:01-30

Am working on this project using react js/Material UI

Now I want to get the ID of the data that I had searched. this is my code so far

<Autocomplete
   id="free-solo-demo"
   freeSolo
   options={data.map((option) => option.item)}
   renderInput={(params) => <TextField {...params} label="Search" />}
   onChange={(event, value) => setSearch(value)}
 />

my database

enter image description here

In the above, I was able to store the searched data but what I really want is to get the ID only. Hope someone can point out what am missing here.

thanks

CodePudding user response:

I think it would be better to convert data to what mui autocomplete can handle (array of objects with label and value properties)

so you can convert it in this way :

options={data.map(opt=>({label:opt.title,value:opt.id}))}

and add

getOptionLabel={(option) => {
        return option.label;
      }}

for only showing label for each option

and the value of the search state would be sth like this: {label:'The Game',value:1} so the id would be search.id

CodePudding user response:

I believe if your author model includes all three fields and if you set the selection to that model, then you should be able to access the id from the selection.

not my code but on the onChange event here:


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

const NbaAutocomplete = () => {
  const [selectedTeam, setSelectedTeam] = useState(null);

  console.log(selectedTeam);

  return (
    <Autocomplete
      id="nba teams"
      options={nbaTeams}
      renderInput={params => (
        <TextField {...params} label="NBA Team" variant="outlined" />
      )}
      getOptionLabel={option => option.name}
      style={{ width: 270 }}
      value={selectedTeam}
      onChange={(_event, newTeam) => {
        setSelectedTeam(newTeam);
      }}
    />
  );
};

export default NbaAutocomplete;

Ref to the creator of that example / not me:

https://plainenglish.io/blog/how-to-use-the-autocomplete-component-in-material-ui-11a7132d2b71

You can also probably do it in options, by setting getOptionLabel to model->title and then parsing the model for the id from the selection model. Maybe useful example similar to your model: https://mui.com/joy-ui/react-autocomplete/

  • Related