user1177860 user1177860 - 12 days ago 8
React JSX Question

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

Answer

Yep, you'll have to add an onChange handler for the select element. Leo provided an answer for you but probably isn't optimal as every time the event fires, a new callback is created. Although at the scale your app probably doesn't require this level of optimisation. Anyway, I would probably rewrite things to extend from the React.Component class:

import React from 'react';

class UIPrintChart extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 'PNG'
    };
    this.handleChange = this.handleChange.bind(this);
    this.handlePrint = this.handlePrint.bind(this);
  }

  handlePrint() {
    if (this.state.value) {
      console.log(this.state.value);
    }
  }

  handleChange(e) {
    this.setState({ value: e.target.value });
  }

  render() {
    return (
      <div>
        <select onChange={this.handleChange}>
          <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
    );
  }
}

export default UIPrintChart;

I also simplified your handlePrint function, but you can implement this however you like :) Hope this helps!