简体   繁体   中英

How to retrieve data from custom attribute on option tag in React

I have a form with a select dropdown with options that are built by looping over an object. Each option has an associated value attribute and a custom attribute data .

I can retrieve the value just fine but I cannot access the data attribute. I tried following a JavaScript pattern found here but to no avail. The value returned is undefined .

Here is the component with the form:

import React from 'react';
import Option from './Option';

class AddmenuItemForm extends React.Component {
  createMenuItemTest(event) {
    event.preventDefault();

    const menuItem = {
      subsectionObjectId: this.subsectionObjectId.value,
      orderIndex: this.subsectionObjectId.selectedIndex.data,
    }

    this.props.addMenuItem(menuItem);

    this.menuItemForm.reset();
  }

  render() {
    const { subsections } = this.props;

    return (
      <div>
        <form ref={(input) => this.menuItemForm = input} onSubmit={(e) => this.createMenuItemTest(e)}>
          <select
            ref={(input) => this.subsectionObjectId = input}
            className="input mtm">
            {
              Object
                .keys(subsections)
                .map(key => <Option key={key} id={key} details={subsections[key]} />)
            }
          </select>

          <button type="submit">Add New</button>
        </form>
      </div>
    );
  }
};

export default AddmenuItemForm;

And here is the Option component:

import React from 'react';

class Option extends React.Component {
  render() {
    const { details } = this.props;
    const key = this.props.id;

    return (
      <option value={key} data={details.numberMenuItems}>
        {details.name}
      </option>
    )
  }
}

export default Option;

Rendered HTML looks like this (the <select> portion):

<select>
  <option value="KhEncads5F" data="11">Lunch</option>
  <option value="rxGeTpqSDF" data="2">Dinner</option>
</select>

Is there a way to retrieve the extra piece of info on the selected <option> tag?

Using the ref you have to your DOM element you can access the and the selectedOptions :

this.subsectionObjectId.selectedOptions[0].getAttribute('data-items')

Check this working example:
https://jsfiddle.net/1rmftx4z/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM