DEV Community

poshiya parth s
poshiya parth s

Posted on • Edited on

Mastering Multi-Select Options with React-Select/Creatable

Content:

React-Select/Creatable is a powerful library that enhances the user experience when dealing with multi-select options in React applications. In this blog post, we will explore how to effectively implement and leverage React-Select/Creatable to create a seamless and intuitive multiple-selection component.

Understanding the Basics
React-Select/Creatable provides a flexible and customizable solution for handling multi-select options. The Creatable component, in particular, allows users to create new options on-the-fly, making it an excellent choice for scenarios where dynamic data entry is required.

Setting Up the Environment
To get started, make sure you have React and React-Select/Creatable installed in your project. You can install it using npm or yarn:

npm install react-select
or
yarn add react-select

Building the Multi-Select Component
The provided code showcases a React component (App) that utilizes React-Select/Creatable for multi-select functionality. Let's break down some key elements:

Filter Options: The filterOptions array defines the types of filters available for selection (e.g., State, Pincode, District).

State Management: The component uses React's useState hook to manage the state of selected parameters (paramsData) and whether the selection is complete (apply).

Dynamic Search Suggestions: The onInputChange function dynamically generates search suggestions based on user input and selected filter options.

Effect Hook: An useEffect hook monitors changes in the selected parameters and triggers the application of filters.

Customization and Styling
React-Select/Creatable provides various customization options to tailor the appearance and behavior of the multi-select component. The components prop is used to override the default behavior of the clear indicator.

Integration in Your Project
To integrate this multi-select component into your project, simply import and render the App component where needed. Customize the styles and appearance according to your project's design guidelines.

Conclusion
React-Select/Creatable simplifies the implementation of a feature-rich multi-select component in React applications. Whether you're managing tags, categories, or any other form of multiple selections, React-Select/Creatable provides an elegant and user-friendly solution.

Start incorporating React-Select/Creatable into your projects today to empower users with a seamless and efficient multi-select experience!

import { useState, useEffect } from "react";
import Creatable from "react-select/creatable";
import { intersection, isEmpty } from "lodash";

const Search = () => {
  let Placeholder = "Search ";
  const filterOptions = [
    {
      label: "State",
      value: "state",
    },
    {
      label: "Pincode",
      value: "pincode",
    },
    {
      label: "District",
      value: "district",
    },
  ];

  const [apply, setApply] = useState(false);

  const [paramsData, setParamsData] = useState([]);

  const [searchOptions, setSearchOptions] = useState([]);

  const onChange = (params) => {
    if (isEmpty(paramsData)) {
      setParamsData(params);
    } else if (
      disableInput &&
      isEmpty(params) &&
      Placeholder === "Search Admin"
    ) {
      setParamsData([]);
    } else if (
      disableInput &&
      !isEmpty(params) &&
      Placeholder === "Search Admin"
    ) {
      return;
    } else {
      setParamsData(params);
    }
  };

  const disableInput = paramsData.length === filterOptions.length;
  const onInputChange = (seachKey) => {
    if (!seachKey) {
      setSearchOptions([]);
      return;
    } else if (seachKey.length !== 0) {
      const paramsFieldValues = paramsData.map((param) => param.field);
      const filterOptionValues = filterOptions.map((option) => option.value);

      const commonValues = intersection(paramsFieldValues, filterOptionValues);

      const filteredFilterOptions = filterOptions.filter(
        (option) => !commonValues.includes(option.value)
      );
      const options = filteredFilterOptions.map((option) => {
        return {
          label: `${option.label} : ${seachKey}`,
          value: seachKey,
          field: option.value,
        };
      });

      setSearchOptions(options);
    } else {
      const options = filterOptions.map((option) => {
        return {
          label: `${option.label} : ${seachKey}`,
          value: seachKey,
          field: option.value,
        };
      });
      setSearchOptions(options);
    }
  };

  useEffect(() => {
    if (isEmpty(paramsData)) {
      setApply && setApply(!apply);
    }
  }, [paramsData]);
  return (
    <div className="!cursor-pointer">
      <Creatable
        classNamePrefix="multitag provider_modal"
        options={searchOptions}
        placeholder={Placeholder}
        isMulti
        value={!isEmpty(paramsData) ? paramsData : null}
        className=" w-[350px] maxSm:w-[290px]"
        onChange={onChange}
        onInputChange={onInputChange}
        isClearable
        components={{
          ClearIndicator: () => null,
        }}
      />
    </div>
  );
};

export default Search;






Enter fullscreen mode Exit fullscreen mode

Top comments (0)