React js
React Select Dropdown onchange | React Select Box Example
In this example, we will take a simple “category” select box and add onchange event with handleChange() then we will assign a value on state variable array. Then on submitting an event, we will take those values with the state variables.
So, let’s see bellow preview and code:
Example Code:
import React, { Component } from 'react';
import { render } from 'react-dom';
class App extends Component {
constructor() {
super();
this.state = {
category: 'php'
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({category: event.target.value});
}
handleSubmit(event) {
console.log(this.state);
event.preventDefault();
}
render() {
return (
<div>
<h1>React Select Dropdown onChange Example</h1>
<form onSubmit={this.handleSubmit}>
<strong>Select Category:</strong>
<select value={this.state.category} onChange={this.handleChange}>
<option value="php">PHP</option>
<option value="laravel">Laravel</option>
<option value="angular">Angular</option>
<option value="react">React</option>
<option value="vue">Vue</option>
</select>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
render(<App />, document.getElementById('root'));
Output:
{category: "react"}