Skip to content

Instantly share code, notes, and snippets.

@sibelius
Last active March 8, 2019 17:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sibelius/aec6945f0a96d663db92d0318fa7f925 to your computer and use it in GitHub Desktop.
Save sibelius/aec6945f0a96d663db92d0318fa7f925 to your computer and use it in GitHub Desktop.
useSelectRows is a hook that manage a list of selected items, so you don't have to
const MyUserSelectableList = ({ users ) => {
const { onRowCheck, isRowSelected } = useSelectedRows();
return (
<>
{users.map(user => (
<>
<Checkbox value={isRowSelected(user)} onChange={(value) => onRowCheck(user, value)} />
<span>{user.name}</span>
</>
)}
</>
);
}
import { useState } from 'react';
type Node = {
id: string;
};
export const useSelectedRows = () => {
const [selectedRows, setSelectedRows] = useState<Node[]>([]);
const onRowCheck = (node: Node, checkedState: boolean) => {
if (checkedState) {
const rowIndex = selectedRows.findIndex(({ id }) => node.id === id);
if (rowIndex === -1) {
return;
}
setSelectedRows([...selectedRows.slice(0, rowIndex), ...selectedRows.slice(rowIndex + 1)]);
return;
}
setSelectedRows([...selectedRows, node]);
};
const isRowSelected = ({ id }: Node) => selectedRows.findIndex(node => node.id === id) > -1;
const onRowCheckAll = (selectedRows: Node[]) => setSelectedRows(selectedRows);
return {
onRowCheck,
isRowSelected,
selectedRows,
onRowCheckAll,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment