Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select All / Unselect All option in react-select

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?

like image 377
jonidelv Avatar asked Aug 24 '18 09:08

jonidelv


2 Answers

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
    />
  );
};
like image 171
Mihhail Lapushkin Avatar answered Sep 20 '22 14:09

Mihhail Lapushkin


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.

like image 28
Esin ÖNER Avatar answered Sep 16 '22 14:09

Esin ÖNER