Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
            )
    }
});
like image 992
user1177860 Avatar asked Nov 28 '16 12:11

user1177860


People also ask

How do you get the selected option value in React?

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.

How do you get selected option text in react JS?

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.

How do I get select option onChange in React?

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.


1 Answers

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>
like image 75
Lyubomir Avatar answered Sep 22 '22 07:09

Lyubomir