I have looked and tried the solutions from other questions, but I cannot seem to get it to work. The problem I am facing is that event.target.id and event.target.value do not work here. I have done some research and found out why. Now I just need a way to get the "id" from the selectfield
How do I grab the id, in order to make this function work?
Here I have the select:
<SelectField
id="category"
floatingLabelText="Category"
value={this.state.value}
onChange={this.updateTask.bind(this)}
>
<MenuItem disabled={true} primaryText="Choose A Category" />
<MenuItem value="delivery" primaryText="Delivery" />
<MenuItem value="dog walking" primaryText="Dog Walking" />
<MenuItem value="house cleaning" primaryText="House Cleaning" />
</SelectField>
And here is the function:
updateTask(event, index, value) {
event.preventDefault();
let updated = Object.assign({}, this.state.task);
updated[event.target.id] = event.target.value;
this.setState({
task: updated,
value: value,
});
}
Sadly, it's not possible to pass a JSON-Object as value to the above Selects "onChange" method, or - better said - it is possible, but then MaterialUI injects the value stored in the MenuItem (which is now a JSON Object) into the textField of the SelectMenu - so it displays nothing because you can't alter how the value should be displayed. So as of right now, as much as I know, it's only possible to pass one argument via event.target.value. If you need more arguments, like an index as an example, I did accomplish it like this:
In the "onChange" prop of the Select, accept two arguments: the first one is the event to extract the value from, the second one is child-object which was clicked, as is documented here: https://material-ui.com/api/select/
Now you can access the value from event.target.value as well as access any unique property of the child (which you defined first) via child.props.[yourVariable]
in the MenuItem's declaration; set your id as a prop for the menuItem
{this.state.availableDays.map((day, i) => {
return (
<MenuItem id={i} value={day.key}>{day.key}</MenuItem>
)
})}
in the Select's "onChange" Method; accept event and child as arguments; access child.props.[yourVariable]
onChange={(event, child) => {this.setState({currentDayString: event.target.value, currentDayIndex: child.props.id}) ,this.displayDataForThisDay() }}
I do realize this question was asked a year ago; but maybe my answer is of help for anyone searching for an answer for this very question
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With