1

I'm trying to get the 'key' value of my dynamic dropdown list as follows:

searchSubmit(e){    
  const s = e.target.value;
  alert(s);
}

my dropdown list is as follows:

<select
  className="textboxstyle"
  onChange={this.searchSubmit}
>
  <option key='-1'>Select Brand</option>
  <option key='0'>ALL</option>
  {optionItems}
</select>

And my dynamic drop-down is populated as follows,

let brands = this.state.brands;
let optionItems = brands.map((brand) =>
  <option key={brand.id}>{brand.name}</option>
);

But when I select option, alert display the name of the selected value, not the key. How to get the 'key' value? Thanks

1 Answer 1

2

The key prop is used by React to differentiate between all the elements in an array. If you want value to be the id of the brand, you can use it as value as well as key.

Example

class App extends React.Component {
  state = {
    brands: [{ id: 1, name: "Foo" }, { id: 2, name: "Bar" }]
  };

  searchSubmit = e => {
    const { value } = e.target;
    alert(value);
  };

  render() {
    const { brands } = this.state;

    return (
      <select onChange={this.searchSubmit}>
        <option value="-1">Select Brand</option>
        <option value="0">ALL</option>
        {brands.map(brand => (
          <option value={brand.id} key={brand.id}>
            {brand.name}
          </option>
        ))}
      </select>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

and how do I get the 2 values ​​brand.key and brand.name?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.