Could someone help me with the sorting as something doesn’t want to work for me.
I want to be able to click on a table cell and sort 1 column alphabetically by string, the rest ascending/descending depending on the click, i.e. one click ascending, the other descending.
I have two array of objects, for columns and for rows.
const columns = [{id: 1, title1: "one", title2: "two", title3: "three", title4: "four", title5: "five", title6: "six", title: "seven"}]
const rows = [{id: 1, value1: "", value2: 20, value3: 30, value4: 40, value5: 50, value6: 90, value7: 39}]
export default function MyComponent<T extends string>({
columns,
rows,
}: types.Data<T>) {
const [sortSomething, setSortSomething] = useState(rows);
const sorMyCols = () => {
rows.map(item => item.value1).sort((a, b) => a - b);
};
const [toggleIcon, setToggleIcon] = useState<{ [index: number]: boolean }>({});
const handleToggleIcon = (index: number) => {
setToggleIcon((prevState) => ({
...prevState,
[index]: !prevState[index],
}));
};
// my sort function
const sortTable = () => {
rows.map(item => item.value2).sort((a, b) => a - b);
};
<Table>
<TableBody>
{columns .map((data, rowIndex) => (
<TableRow key={rowIndex}>
{Object.entries(data).map(([key, value], cellIndex) => (
<TableCell
key={key}
onClick={() => handleToggleIcon(cellIndex), sortTable()}>
<span>{value}</span>
{toggleIcon[cellIndex] ? (
<ArrowUpward />
) : (
<ArrowDownward />
)}
</TableCell>
))}
</TableRow>
))}
<TableBody>
{sorMyCols.map((item, in) => (
<TableRow key={item.id}>
{Object.entries(item).map(([key, value], index) => (
<TableCell key={key}>
{value}
</TableCell>
))}
</TableRow>
</TableBody>
</Table>
);