Fred
Fred

Reputation: 202

How to get specific value when changing Autocomplete component of Material UI

I am trying to implement the autocomplete component of the ui material, I would like that when there is a change in the selection, I would capture the ID of the selected team.

As below, i'm getting the team name, how would you get the ID?

Complete code: Edit autocomplete material-ui example (forked).

import React, { useCallback } from 'react';
import { Field } from 'formik';
import MuiTextField from '@material-ui/core/TextField';
import {
  Autocomplete,
  AutocompleteRenderInputParams,
} from 'formik-material-ui-lab';


const teams = [
  { id: 1, name: 'Barcelona' },
  { id: 2, name: 'Real Madrid'}
];

const Teams: React.FC = () => {
  const handleShowId = useCallback((event, value) => {
      alert(value)
  },[])

  return (
    <Field
        name="teams"
        component={Autocomplete}
        options={teams}
        size="small"
        getOptionLabel={(option: any) => option.name}
        onInputChange={handleShowId}
        renderInput={(params: AutocompleteRenderInputParams) => (
        <MuiTextField
            {...params}
            label="Select"
            variant="outlined"
        />
        )}
    />
  )
};

export default Teams;

Upvotes: 3

Views: 411

Answers (1)

LuisMendes535
LuisMendes535

Reputation: 536

onInputChange doesn't return the id. You can get the id though by targeting the selected option and look upon your array of options.

const handleShowId = React.useCallback((event) => {
 const selectedId = event.target.id.split('option-').pop();
 alert(teams[selectedId].id);
}, []);

Upvotes: 1

Related Questions