#MultiSelect clear button
1 messages · Page 1 of 1 (latest)
Hi, I would go with controlled component where each multiselect have own state and then in onClick function for button clear each state https://mantine.dev/core/multi-select/#controlled
If all multiselects are part of larger form, maybe in this case I would use some form library like react-hook-form to avoid renders, but yeah... it depends on case
`import "@mantine/core/styles.css";
import { useState } from "react";
import { MantineProvider, MultiSelect } from "@mantine/core";
export default function App() {
const [value, setValue] = useState<string[]>(["React"]);
return (
<MantineProvider>
<button
onClick={() => {
setValue([]);
}}
>
Clear all MultiSelect
</button>
<MultiSelect
data={["React", "Angular", "Vue", "Svelte"]}
value={value}
onChange={setValue}
/>
</MantineProvider>
);
}`
like this ?
if it's just one multiselect, use the clearable prop
https://mantine.dev/core/multi-select/#clearable
otherwise like zuodziejovzky pointed out you'd need to make them controllable yeah
Yes, something like that. You can create useState for each multiselect and inside onClick in button call: setValue([]) (for each state).
Also you can create one state to store values from all multiselects like:
const [multiSelectValues, setMultiSelectValues] = useState<{ firstSelect: string[], secondSelect: string[], ...etc }>({ firstSelect: [], secondSelect: [], ...etc })
And use it like that:
<MultiSelect data={[...]} value={multiSelectValues.firstSelect} onChange={(value) => setMultiSelectValues((prev) => ({ ...prev, firstSelect: value })} />
(for next multiselect it will be secondSelect , ...etc.)
And to clear values from all multiselect you can just call setMultiSelectValues with default values defined in state, inside onClick function
when you say "clear selected values in all MultiSelect components" do you just mean "all the selected options in one MultiSelected component", or "multiple MultiSelect component, one action empties all of them at once"?
a secondary approach is to use useListState for this, you'll be able to avoid needing to manually define firstSelect, secondSelect etc and have an array of arrays instead
https://mantine.dev/hooks/use-list-state/
Oh, I didn't know about use-list-state 🙂
multiple MultiSelect component, one action empties all of them at once
Thank you for your answers, I will study these materials
ah, so with the useListState approach you'll basically be able to do like value={values[i]} with onChange={(newValue) => handlers.setItem(i, newValue)}