javascriptreactjsreact-bootstrap-typeahead

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 enter image description here

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

Thanks in advance.


Solution

  • 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>