A hook to easily select items based on an array

useSelectedItems

Easily select items based on an array

Check out the example

๐Ÿ‘ท Installation

With Yarn

yarn add use-selected-items-hook

With NPM

npm install use-selected-items-hook

๐Ÿ“Œ Usage

import useSelectedItems from "use-selected-items-hook";

   const [
    selectedItems,
    listItems,
    { toggleItem },
   ] = useSelectedItems<ItemType>({
    itemIdentifier: "id",
    items,
  });

  const handleClick = (item) => () => {
    toggleItem(item);
  };

  return (
     {
      listItems.map((item) => {
         // You're able to apply a specify style to a selected item
         const itemClasses = classNames("cursor-pointer border-white border-solid", {
            "border-black": item.selected,
         });

         return (
            <div
               key={item.id}
               className={itemClasses}
               onClick={handleClick(item)}
            >
               <p>
                  {item.name}
               </p>
            </div>
         );
      })
   }
  )

As showed in the example above, youโ€™re able to pass an array of items from any type of source, as long it has a unique identifier in order to compare the items.

๐Ÿ’ป API

useSelectedItem

   export type Item<T> = T & {
      selected: boolean
   };

   export interface Actions<T> {
      toggleItem: (T) => void,
      setSelectedItems: Dispatch<SetStateAction<T[]>>,
      setItemsList: Dispatch<SetStateAction<Item<T>[]>>
   }

   useSelectedItems<T>({
      itemIdentifier: string | number,
      items: T[],
   }): [T[], Item<T>[], Actions<T>];

The two arrays returned are the following: selectedItems and listItems.

  • selectedItems: The items currently selected and that might be send for an API.
  • listItems: The items with the boolean state of selected, which youโ€™re able to map and show an visual feedback.

The actions allow you to manipulate items.

  • toggleItem: Toggle the selected item, by changing the state and pushing or removing from the array.

๐Ÿ”จ Builds

  • es (EcmaScript module)
  • cjs (CommonJS)

๐Ÿ“ฎ Faq

Question: What are the tecnologies used in this project?

Answer: The tecnologies and libraries used in this project are React + TypeScript and Immutability Helper to handle the array manipulation.

๐Ÿ› Issues

Feel free to file a new issue with a respective title and description on the the useSelectItems hook repository. If you already found a solution to your problem, I would love to review your pull request! Have a look at our contribution guidelines to find out about the coding standards.

๐ŸŽ‰ Contributing

Check out the contributing page to see the best places to file issues, start discussions and begin contributing.

Download Details:

Author: LauraBeatris

Demo: https://use-selected-items-hook.vercel.app/

Source Code: https://github.com/LauraBeatris/use-selected-items-hook

#reactjs #react #javascript

A hook to easily select items based on an array
3.25 GEEK