react-select + allOption

alex_escalante

Alex Escalante

Posted on August 19, 2017

react-select + allOption

If you are using the React library react-select, you will find it doesn’t implement a “select all” option. It’s not difficult to implement this feature by yourself, just have a look at the following gist. You will even find how to make a localization wrapper on top of your control, in case you need it.

Take a look at the relevant stuff:

// specify props.allowSelectAll = true to enable!
const Select = props => {
  if (props.allowSelectAll) {
    if (props.value.length === props.options.length) {
      return (
        <ReactSelect
          {...props}
          value={[props.allOption]}
          onChange={selected => props.onChange(selected.slice(1))}
        />
      );
    }

    return (
      <ReactSelect
        {...props}
        options={[props.allOption, ...props.options]}
        onChange={selected => {
          if (
            selected.length > 0 &&
            selected[selected.length - 1].value === props.allOption.value
          ) {
            return props.onChange(props.options);
          }
          return props.onChange(selected);
        }}
      />
    );
  }

  return <ReactSelect {...props} />;
};
Enter fullscreen mode Exit fullscreen mode

You will find the full gist at:

https://gist.github.com/AlexEscalante/251032be95767366742fce75bdfa269b

Please drop a line if you find this useful or have any comment!

💖 💪 🙅 🚩
alex_escalante
Alex Escalante

Posted on August 19, 2017

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related