useSorting
useSorting hook provides a simple way of sorting big chunks of data by key and direction.Import
import { useSorting } from "@prismane/core/hooks";
Usage
function Demo() { const items = [ { name: "Apple", quantity: 10 }, { name: "Banana", quantity: 5 }, { name: "Cherry", quantity: 15 }, { name: "Date", quantity: 8 }, ]; const { sorted, key, direction, setKey, toggleDirection } = useSorting( items, "name" ); return ( <Stack as={Center}> <Button onClick={() => setKey("name")}>Sort by Name</Button> <Button onClick={() => setKey("quantity")}>Sort by Quantity</Button> <Button onClick={toggleDirection}>Toggle Order</Button> <Stack mt={fr(6)}> {sorted.map((item, index) => ( <Text key={index}> {item.name} - {item.quantity} </Text> ))} </Stack> <Text> Sorting by: <Text as="strong">{key}</Text> (Order:{" "} <Text as="strong">{direction}</Text>) </Text> </Stack> ); }
API
Parameters
Name | Type | Description | Default |
---|---|---|---|
data | any[] | The data that will be tracked. | - |
initialKey | string / null | The key by which the data will be sorted. | null |
initialDirection | 'asc' / 'desc' | The direction by which the data will be sorted. | 'asc' |
options | useSortingOptions | The options of the hook. | { resetDirectionOnKeyChange: true } |
type useSortingOptions = { resetDirectionOnKeyChange?: boolean; };
Return Value
Name | Type | Description |
---|---|---|
sorted | any[] | The sorted data. |
key | string | The current key by which the hook is sorting. |
direction | 'asc' / 'desc' | The current direction by which the hook is sorting. |
setKey | (key: string) => void | The function that sets the new key by which the hook will sort. |
setDirection | (direction: 'asc' / 'desc') => void | The function that sets the new direction by which the hook will sort. |
toggleDirection | () => void | The function that toggles the direction by which the hook will sort. |