WIKIEHELP
Health and Fitness

How to use Multi Select Option in React

React: Multi Select Option in React Functional and Class based Component

React Functional Component

React functional component is easy to use for using multi-select in functional Components is easy to do. All you have to do is use the map function in option.value field. It’s because it adds the selected values in the array easily.

How to use Multi Select Option in React
© Poistronx.com

for creating multi-select in react functional component. Create a select option with the help of bootstrap then use onchange method to select the option. After that declare this function method and setState of the current target selected option using e.target.selectedOption. You also have to map each value using the map function.

Here is the code for your reference:

import React, { useState } from "react"

function MulitSelectCategry() {

const [selectedCategories, setSelectedCategories] = useState([])

function addCategoryChange(e) {

const selectedOptions = [...e.target.selectedOptions].map(o => parseInt(o.value))

setSelectedCategories(selectedOptions)

}

console.log(selectedCategories)

return (

<div className="container mt-5">

<h2 className="mb-3">Multi Select Category</h2>

<form>

<div className="form-group">

<label id="SelectCategory">Select Categories</label>

<select

multiple

className="form-control"

onChange={e => addCategoryChange(e)}

>

<option value="1">Jeans</option>

<option value="2">Shirts</option>

<option value="3">T-Shirts</option>

<option value="4">Men</option>

<option value="5">Women</option>

</select>

</div>

</form>

</div>

)

}

export default MulitSelectCategry

We hope this article helped you to know about Diabetes: Everything You Need to Know About This Disease. You may also want to see our guide on What Too Much Sodium Do To Your Body, Salt Side Effects, and How To Maintain Hygiene In Intimate Area.

If you liked this article, then please subscribe to our YouTube Channel for Programming, Health, and fitness videos. You can also find us on Twitter and Facebook.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More