Is it possible to have the 'Select All / Unselect All' option in react-select? Is this something that is built in, or I have to do it my self?
At the company where I work we've made a wrapper around react-select
with some additional features and styling. One of the features is Select/Unselect All.
Here is a link to page that demoes the component:
https://topia.design/components/multi-select/
Here is the approach that I've used to implement Select/Unselect All:
https://codesandbox.io/s/distracted-panini-8458i?file=/src/MultiSelect.js
import React, { useRef } from "react";
import ReactSelect from "react-select";
export const MultiSelect = props => {
// isOptionSelected sees previous props.value after onChange
const valueRef = useRef(props.value);
valueRef.current = props.value;
const selectAllOption = {
value: "<SELECT_ALL>",
label: "All Items"
};
const isSelectAllSelected = () =>
valueRef.current.length === props.options.length;
const isOptionSelected = option =>
valueRef.current.some(({ value }) => value === option.value) ||
isSelectAllSelected();
const getOptions = () => [selectAllOption, ...props.options];
const getValue = () =>
isSelectAllSelected() ? [selectAllOption] : props.value;
const onChange = (newValue, actionMeta) => {
const { action, option, removedValue } = actionMeta;
if (action === "select-option" && option.value === selectAllOption.value) {
props.onChange(props.options, actionMeta);
} else if (
(action === "deselect-option" &&
option.value === selectAllOption.value) ||
(action === "remove-value" &&
removedValue.value === selectAllOption.value)
) {
props.onChange([], actionMeta);
} else if (
actionMeta.action === "deselect-option" &&
isSelectAllSelected()
) {
props.onChange(
props.options.filter(({ value }) => value !== option.value),
actionMeta
);
} else {
props.onChange(newValue || [], actionMeta);
}
};
return (
<ReactSelect
isOptionSelected={isOptionSelected}
options={getOptions()}
value={getValue()}
onChange={onChange}
hideSelectedOptions={false}
closeMenuOnSelect={false}
isMulti
/>
);
};
I inspired from Alex's method, but i changed some section of his code. There is a example i prepared, if you still need, you can check.
And also I made another example for the case that there is too much data, i solved performance problem with react-window and i changed input value if user select more than 5 items.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With