agm1984
agm1984

Reputation: 17132

In React, how to grab custom data when options are selected in <select> elements

I have a <select> element that displays a list of Countries.

When the user selects one, the selected value is a name, like "Canada" but I need to make a query that uses the serial number we use for Canada.

How do I get that serial number out of the stateless functional select component and into the parent container?

Here is the relevant code:

dumb component

const GeoSelect = function selectFromGeoTree({ ... }) {
  ...
  return (
    <select
      id={name}
      className={maybeHasError}
      name={name}
      onChange={onChange}
      {...input}
    >
      <option
        value={0}
        className="edit_empty"
      >
        {placeholder}
      </option>
      {options && options.map(opt => (
        <option
          key={opt.serialNumber}
          value={opt.label}
          className="edit_filled"
          id={opt.id}
        >
          {opt.label}
        </option>
      ))}
    </select>
  )
}

container

<Field
  label="Country"
  component={FormSelectFromObject}
  name="country"
  placeholder="Select Country"
  options={this.state.countries}
  onChange={e => console.log('ON SELECT', e.target)}
  required
/>

enter image description here

I am looking to do as concisely as possible something like:

onChange={(id) => this.getRegions(id)}

to make a query that gets a list based on that ID.

The data structure that goes into the <select> element looks like this:

this.state.countries = [
  { id: '9s87f698d7f', label: 'Canada' },
  { id: 'dsei487g4e4', label: 'USA' },
]

How do I get that ID back up into the parent when the user selects one of the options?

My leading thought so far is to do something like this:

onChange={(e) => {
  const { id } = this.state.countries.find(country => country.label === e.target.value)
  this.getRegionsById(id)
}}

Upvotes: 0

Views: 64

Answers (1)

anomaaly
anomaaly

Reputation: 841

I would set your option value to the serial number you need. Then onchange for the select element get e.target.value, which should be the serial number.

Upvotes: 2

Related Questions