Categories
javascript reactjs

Get select option value on submit with React

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>
)
}
});

I would recommend using refs instead of state.

<select ref="imageType">
<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>
handlePrint() {
if (this.refs.imageType) {
console.log(this.refs.imageType.value);
}
}