0

I have child component which represents simple . My idea is to pass some fetched data to its parent component. I have state like this:state: { countries: [] }, and I fetched data to it in componentDidMount(). state.countries is filled with some id and countryName values. When I write code like this

   <select
      name="country"
      defaultValue="country"
      onChange={this.onChangeHandler}
    >
      <option disabled value="country">
        Select country
      </option>
      {countries.map(({ id, countryName }) => (
        <option key={id} value={id}>
          {countryName}
        </option>
      ))}
    </select>

it works perfectly. But when I try to pass attributes through props like this:

<Select 
          name="country"
          defaultValue="country"
          onChange={this.onChangeHandler}
          defaultOption="Select Country"
          apiResult={countries}
          dataId={countries.id}
          dataName={countries.countryName}
          disabled="disabled"
        />

it fails. Parent component looks like this:

const { name, label, onChange, defaultValues, apiResult, defaultOption, dataId, dataName, disabled } = props;
<select name={name} value={defaultValues} onChange={onChange} id="">
    <option disabled={disabled} value={defaultOption}>{defaultOption}</option>
    {apiResult.map(() => (
      <option key={dataId} value={dataId}>
        {dataName}
      </option>
    ))}
  </select>

What am I doing wrong? Thanks in advance!

Jonast92
  • 4,964
  • 1
  • 18
  • 32
Opie Winston
  • 69
  • 2
  • 10
  • Possible duplicate of [How to update parent's state in React?](https://stackoverflow.com/questions/35537229/how-to-update-parents-state-in-react) – Jonast92 Jun 13 '19 at 14:13

1 Answers1

0

.map method must be used in a different way. As first argument you get the current item on the sequence. So:

<select name={name} value={defaultValues} onChange={onChange} id="">
    <option disabled={disabled} value={defaultOption}>{defaultOption}</option>
   {apiResult.map((apiItem) => (
     <option key={apiItem.key} value={apiItem.id}>
       {dataName}
     </option>
   ))}
  </select>

So you can call the component like:

<Select 
      name="country"
      defaultValue="country"
      onChange={this.onChangeHandler}
      defaultOption="Select Country"
      apiResult={countries}
      disabled="disabled"
    />

dataId={countries.id} and dataName={countries.countryName} make no sense if countries is an array.

keul
  • 7,673
  • 20
  • 45