简体   繁体   中英

React <Typeahead> get selected array object id

I have an array

lookuplist = [
  { name: "Dave", id: 4780127, capital: "Montgomery", region: "South" },
  { name: "Jessie", id: 710249, capital: "Juneau", region: "West" },
  { name: "Steven", id: 6392307, capital: "Phoenix", region: "West" },
];

I am using Typeahead in a form

<FormGroup>
  <label className="form-control-label" htmlFor="input-email">
    Account
  </label>
  <Typeahead
    id="input-account"
    onChange={setSelected}
    options={lookuplist}
    placeholder="Choose a Account..."
    selected={selected}
    filterBy={["name"]}
    labelKey={(lookuplist) => `${lookuplist.name} (${lookuplist.id})`}
  />
</FormGroup>

All the functionalities of typeahead are working good, The value set in type ahead is name (id) which is a label key , What I need is only id of the selected option.

For example, If I select "Dave" the typeahead value=4780127 which is an "id" of the array.So that i can get the "id" of an array value 在此处输入图像描述

code: https://codesandbox.io/s/brave-sound-pzse0?file=/src/App.js

Thanks in advance.

I think I understand what your problem is, you want to save the selected id to state instead of the entire object right?

You could try the following, so add a function handling the change:

const handleChange = value => {
    setSelected(value[0].id)
};

And then pass on the handleChange to the onChange prop and for the selected prop you filter the lookuplist based on the saved id:

<FormGroup>
  <label className="form-control-label" htmlFor="input-email">
    Account
  </label>
  <Typeahead
    id="input-account"
    onChange={handleChange}
    options={lookuplist}
    placeholder="Choose a Account..."
    selected={lookuplist.filter(x => x.id === selected)}
    filterBy={["name"]}
    labelKey={(lookuplist) => `${lookuplist.name} (${lookuplist.id})`}
  />
</FormGroup>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM