Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: access data-attribute in <option> tag

I have this select JSX:

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

with options being:

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 data-country of the option selected, since the value is accessed by e.target.value, and e.target.dataset is the dataset of the select tag and not the option 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?

Thanks

like image 292
Augustin Riedinger Avatar asked Feb 19 '16 17:02

Augustin Riedinger


Video Answer


3 Answers

I find @bjfletcher even more elegant than mine, but I'll report for the records:

I access the <option> DOM element through e.target.options[e.target.selectedIndex] in the onChange method:

  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);
  },

Not sure of the compatibility though.

like image 139
Augustin Riedinger Avatar answered Oct 16 '22 18:10

Augustin Riedinger


I would pass around just 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 slug:

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'd replace the .find with a forEach or whatever JS you use if not ES6 capable.)

like image 30
bjfletcher Avatar answered Oct 16 '22 19:10

bjfletcher


I think your best bet would be 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
    ...
},
like image 2
Jake Haller-Roby Avatar answered Oct 16 '22 18:10

Jake Haller-Roby