-
-
Save zaguiini/b43efc1bf63dc069a0ef6c1401b52a1a 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MyUserSelectableList = ({ users ) => { | |
const { onRowCheck, isRowSelected } = useSelectedRows(); | |
return ( | |
<> | |
{users.map(user => ( | |
<> | |
<Checkbox value={isRowSelected(user)} onChange={(value) => onRowCheck(user, value)} /> | |
<span>{user.name}</span> | |
</> | |
)} | |
</> | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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