What I want to do is get the value of the selected <option> from the <select> elemenet however in my current code, I keep getting an error saying:
cannot read property 'value' of null.
This is very frustrating considering I've tried the methods I found online and yet it still doesn't work properly. Any help would be appreciated, thanks!
import React, { Component } from 'react'
class MyClass extends Component{
constructor(props){
super(props);
this.state = {
selectedItem: ""
};
}
onChange() {
var selectedItem = document.getElementById("selectItem").value
this.setState({selectedItem: selectedItem})
}
render(){
return (
<div style={{textAlign: "center"}}>
<select id="selectItem" defaultValue="option1" onChange={this.onChange()}>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
<div>{this.state.selectedItem}</div>
</div>
)
}
}
export default MyClass
I would like it to display what option is being selected within the div. If possible I would also like it to show the defaultValue upon loading the page as well.
onChange={this.onChange()}). You should useonChange={this.onChange}, in any case, usingdocument.getElementByIdin a ReactJS app is not the way to go.