What is the best way to get the vaule of the select option when I click on the submit button in react?
Would I need to add an onChange to the select option as well?
var UIPrintChart = React.createClass({
getInitialState: function () {
return {
value: 'PNG'
}
},
handlePrint(event) {
if (this.state.value == 'PNG') {
console.log('Hello PNG');
}
if (this.state.value == 'JPEG') {
console.log('Hello JPEG');
}
if (this.state.value == 'PDF') {
console.log('Hello PDF');
}
if (this.state.value == 'SVG') {
console.log('Hello SVG');
}
},
render() {
return (
<div>
<select>
<option value="PNG">PNG Image</option>
<option value="JPEG">JPEG Image</option>
<option value="PDF">PDF Document</option>
<option value="SVG">SVG Vector Image</option>
</select>
<button className="uk-button uk-button-mini" onClick={this.handlePrint}>Export Chart</button>
</div>
)
}
});
Controlled Components to Get Dropdown Menu Value in React First, we must set up an event listener on the <select> element and define an event handler. In our example, it takes one argument - e (short for event) and calls the setFruit() function. To set the state with the selected value, we access the e. target.
The text of an option is simply the label property of the corresponding item . In your case, to retrieve the text of the selected option, you can do: var selectedItem = this.
To handle the onChange event on a select element in React: Set the onChange prop on the select element. Keep the value of the selected option in a state variable. Every time the user changes the selected option, update the state variable.
Would I need to add an onChange to the select option as well?
Yes, like this:
<select onChange={(e) => this.setState({ value: e.target.value })}>
<option value="PNG">PNG Image</option>
<option value="JPEG">JPEG Image</option>
<option value="PDF">PDF Document</option>
<option value="SVG">SVG Vector Image</option>
</select>
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