React: access the data attribute in the <option> tag

I have this selectJSX:

    <select className="form-control" onChange={this.onChange} value={this.props.value}>
      {options}
    </select>

with parameters:

var options = this.props.options.map((option) => {
  return (<option key={option.slug} value={option.slug} data-country={option.country} data-continent={option.continent}>{option.value}</option>);
});

But I can’t access the selected element of the data-countryselected parameter, since the value refers to it e.target.value, and e.target.datasetis the tag dataset select, not the selected tag:

  onChange: function(e) {
    this.props.onChange(this.props.name, e.target.value, e.target.dataset.continent, e.target.dataset.country);
  },

Is there a fix on this?

thank

+4
source share
3 answers

I would only skip the slug:

var options = this.props.options.map(option => {
    return (
        <option key={option.slug} value={option.slug}>
          {option.value}
        </option>
    );
});

... and then retrieve the data using the bullet:

onChange: function(event, index, value) {
  var option = this.props.options.find(option => option.slug === value);
  this.props.onChange(this.props.name, value, option.continent, option.country);
}

(You would replace .findwith forEachor any other JS that you use if it does not support ES6.)

+4
source

@bjfletcher , , :

<option> DOM e.target.options[e.target.selectedIndex] onChange:

  onChange: function(e) {
    var dataset = e.target.options[e.target.selectedIndex].dataset;
    this.props.onChange(this.props.name, e.target.value, dataset.continent, dataset.country);
  },

.

+8

I think it’s best to use refs.

var options = this.props.options.map((option) => {
  return (<option ref={'option_ref_' + option.slug} ...></option>);
});

onChange: function(e) {
    var selectedOption = this.refs['option_ref_' + e.target.value];
    selectedOption['data-country']; //should work
    ...
},
0
source

Source: https://habr.com/ru/post/1629605/


All Articles