Jonas Praem
Jonas Praem

Reputation: 2444

React native select: Access key / index of selected option

I have this implemented native select as a dropdown component. I can access the selected value with e.target.value. How do I either access the key value or the index of the mapped options:

<div className={`dropdown ${className} ${isInline ? "dropdown--inline" : ""}`}
style={{ width: width + "px", backgroundColor: styles!.dropdownBackgroundColor, borderColor: styles!.borderColor }}
                    >
    <select className="dropdown__portable-select"
         onChange={e => this.selectItem(e.target.value, true, e.target.index)} value={JSON.stringify(selectedValue)} // This line
                        >
    {selectedValue === unselectedValue && unselectedValue !== undefined ?
       <option value="">{unselectedValue}</option>
       : null}
    {options.map((o: any, index: number) => (
      <option key={index} value={JSON.stringify(o)}>{this.renderValue(o)}</option>
    ))}
  </select>
  <div className="dropdown__spacer" style={{ backgroundColor: styles!.borderColor }} />
  <div className="dropdown__icon-container" style={{ color: styles!.iconColor }}>
    <SvgIcon className="dropdown__icon" iconName="material-design/arrow_down_thin" />
  </div>
</div>

The issue is specifically this line:

onChange={e => this.selectItem(e.target.value, true, e.target.index)} value={JSON.stringify(selectedValue)}

e.target.index obviously doesn't exist. Either does e.target.key to address the key={index} in the map function.

How do I access the key or the index property on select ?

Upvotes: 0

Views: 919

Answers (1)

Samuel Vaillant
Samuel Vaillant

Reputation: 3847

There is HTML property called selectedIndex that you can access on a select element.

this.selectItem(e.target.value, true, e.target.selectedIndex)

You cannot access the key because it's a special attribute managed by React.

Upvotes: 1

Related Questions