Easily select items based on an array
yarn add use-selected-items-hook
npm install use-selected-items-hook
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.
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.es
(EcmaScript module)cjs
(CommonJS)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.
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.
Check out the contributing page to see the best places to file issues, start discussions and begin contributing.
Author: LauraBeatris
Demo: https://use-selected-items-hook.vercel.app/
Source Code: https://github.com/LauraBeatris/use-selected-items-hook
#reactjs #react #javascript