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?
refto obtain a reference to the DOM node and use the answer from the SO post you linked in your question.detailsusingsubsections[this.subsectionObjectId.value].