Created
December 22, 2016 19:37
-
-
Save giovanni-d/af071be9d41bae3f03b4263a1a6b1838 to your computer and use it in GitHub Desktop.
Select with multiple="true" in react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import ReactDOM from 'react-dom'; | |
class Select extends Component{ | |
constructor() { | |
super(); | |
this.state = { | |
folders: ['option 0', 'option 1', 'option 3', 'option 4'], | |
values: [] | |
} | |
} | |
handleChange = (e) => { | |
let options = e.target.options; | |
let selectedOptions = []; | |
for(let i = 0; i < options.length; i++) { | |
if( options[i].selected ) { | |
selectedOptions.push(options[i].value); | |
} | |
} | |
this.setState({values: selectedOptions}); | |
} | |
handleSubmit = (e) => { | |
e.preventDefault(); | |
console.log(this.state.values); | |
} | |
render() { | |
return ( | |
<form onSubmit={this.handleSubmit}> | |
<select multiple="true" value={this.state.values} onChange={this.handleChange}> | |
{this.state.folders.map((item, index) => | |
<option value={index} key={index}>{item}</option> | |
)} | |
</select> | |
<button type="submit">Go</button> | |
</form> | |
); | |
} | |
} | |
ReactDOM.render( | |
<Select />, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example: http://jsfiddle.net/x5hz7qz5/