2

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?

David Yeiser
  • 1,438
  • 5
  • 22
  • 33

1 Answers1

7

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/

Dekel
  • 60,707
  • 10
  • 101
  • 129
  • This worked perfectly, thank you! **Note to others**: my original post had a typo and was using `data-items` and `data` interchangeably for the custom attribute. – David Yeiser May 25 '17 at 13:00
  • Hi, I am getting console log for the *value* attr of `option` tag, but it is giving me an `undefined` for *data* attr of it's console log as i am doing the same thing for both so why the data attr is undefined ? https://gist.github.com/mrudangshah/ed86f242e4be6a57cc2eb85fa254b2eb – TMA Dec 04 '19 at 14:03