I’ve been playing around with the multi select drop down in react. I have multiple drop down boxes, and I would like all the options selected in each drop down to be store together in one array. First post lemme know if my formatting is wrong for the question.
What I have currently adds the options selected into the array however, they aren’t removed when removed from the drop down menu on the ui. Also if multiple items are selected in one drop down menu all previous items get re-added to the array (because of the .forEach) but I wasn’t sure how to get the values from each multi drop down.
Code sandbox: https://codesandbox.io/p/sandbox/dropdownhelp-slzjz5
Dropdown component:
import React, { useState } from 'react';
import Select from 'react-select';
const Dropdown = ({ getData }) => {
const options = [
{ value: "blues", label: "Blues" },
{ value: "rock", label: "Rock" },
{ value: "jazz", label: "Jazz" },
{ value: "orchestra", label: "Orchestra" },
];
return (
<>
<div>
<Select
isMulti
options={options}
onChange={e => e.forEach(opt => getData(opt.value))}
/>
</div>
</>
)
}
export default Dropdown
App.jsx:
import React, { useState } from 'react'
import Dropdown from './Dropdown';
import './App.css'
const App = () => {
const [data, setData] = useState([]);
const addData = (values) => {
setData((curData) => {
return [
...curData,
{ id:Math.random(), values },
]
})
}
return (
<>
<Dropdown getData={addData}/>
<Dropdown getData={addData}/>
<Dropdown getData={addData}/>
<Dropdown getData={addData}/>
<Dropdown getData={addData}/>
{console.log(data)}
</>
)
}
export default App
sillylizard46 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.