Skip to main content

withSortableStateDocs

The withSortableState HOC provides stateful management TableHeader sorting. It stores current sort id and sort direction.

Prefer using <Table sortable /> over this HOC.

Result
Loading...
Live Editor
const columns = [
	{
		title: 'Name',
		dataKey: 'name',
	},
	{
		title: 'Age',
		dataKey: 'age',
	},
];

const rows = [
	{
		name: 'Ada Lovelace',
		age: 36,
	},
	{
		name: 'Lord Byron',
		age: 36,
	},
	{
		name: 'Charles Babbage',
		age: 79,
	},
	{
		name: 'Marie Curie',
		age: 66,
	},
];

function sortById(id) {
	return (a, b) => {
		let x = a[id];
		let y = b[id];

		if (typeof x === 'string') {
			x = x.toLowerCase();
		}
		if (typeof y === 'string') {
			y = y.toLowerCase();
		}

		if (x < y) {
			return -1;
		} else if (x > y) {
			return 1;
		} else {
			return 0;
		}
	};
}

function sort(data, id, direction) {
	const sorted = data.sort(sortById(id));

	if (direction === 'desc') {
		sorted.reverse();
	}

	return sorted;
}

const SortableTable = withSortableState(Table);

function Example() {
	const [sortedData, setSortedData] = React.useState(rows);

	return (
		<SortableTable
			id="demo-component"
			onClickSortLabel={(event, { sortId, sortDirection }) => {
				setSortedData([...sort(sortedData, sortId, sortDirection)]);
			}}
		>
			<TableHeader>
				<TableRow>
					<TableCell id="name" sortable>
						Name
					</TableCell>
					<TableCell id="age" sortable>
						Age
					</TableCell>
				</TableRow>
			</TableHeader>
			<TableBody>
				{sortedData.map((row) => (
					<TableRow key={`row-${row.name}`}>
						{columns.map((column) => (
							<TableCell key={`row-${row.name}-${column.dataKey}`}>
								{row[column.dataKey]}
							</TableCell>
						))}
					</TableRow>
				))}
			</TableBody>
		</SortableTable>
	);
}

render(<Example />);

Props