Hướng dẫn tạo Multi Select Dropdown sử dụng React
8th Oct 2022In this tutorial i will explain react multiselect dropdown example. Sometimes we need to create react-bootstrap multiselect dropdown example for our web application. Now in this following tutorial i will show it from scratch.
I will explain step by step explain react multi select dropdown component. Just you need to follow bellow step for how to use multi select dropdown in react. In this following example, we will take one categories array with "PHP", "Laravel" , "Angular" etc. and simply using map loop display dynamic multiple option.
Take one categories
import React, { Component } from 'react'; class MultiSelectDropdown extends Component { constructor() { super(); this.state = { categories: [ {id: 1, value: "PHP"}, {id: 2, value: "Laravel"}, {id: 3, value: "Angular"}, {id: 4, value: "React"} ], selCategories: 'php' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { const selected=[]; let selectedOption=(event.target.selectedOptions); for (let i = 0; i < selectedOption.length; i++){ selected.push(selectedOption.item(i).value) } this.setState({selCategories: selected}); } 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 multiple onChange={this.handleChange.bind(this)}> { this.state.categories.map((item ,i )=> ( <option key={i} value={item.id}>{item.value}</option> )) } </select> <input type="submit" value="Submit" /> </form> </div> ); } } export default MultiSelectDropdown;
Add new comment