Sorting Component using React

kartik goyal
2 min readSep 27, 2023

--

The component to show sort arrows. (up and down arrow)

import {
BiDownArrow,
BiSolidDownArrow,
BiSolidUpArrow,
BiUpArrow,
} from "react-icons/bi";

/**
* To Add the sorting component
* Call the component where it is required
* by Create a state for up down sort and the column name in the parent component
* Call the sortTheData function (passing array and sort component value) with the required param
* as per portal.js, website.js files
*
* @param {*} param0
* @returns
*/
const SortArrow = ({ sortData, setSortData, columnName }) => {
const setUpArrow = () => {
setSortData("up " + columnName);
};
const setDownArrow = () => {
setSortData("down " + columnName);
};
return (
<>
{sortData !== `up ${columnName}` && (
<button onClick={setUpArrow}>
<BiUpArrow />
</button>
)}
{sortData === `up ${columnName}` && (
<button>
<BiSolidUpArrow />
</button>
)}
{sortData !== `down ${columnName}` && (
<button onClick={setDownArrow}>
<BiDownArrow />
</button>
)}
{sortData === `down ${columnName}` && (
<button>
<BiSolidDownArrow />
</button>
)}
</>
);
};

export default SortArrow;

Required State Variable

const [sortData, setSortData] = useState("");

Required function

export const sortTheData = (data, sortBy) => {
const ascSort = (columnName) => {
if (data?.length) {
data.sort((item1, item2) =>
item1?.[columnName] > item2?.[columnName] ? 1 : -1 // -1 to update the sequence
);
// return data;
}
};
const descSort = (columnName) => {
if (data?.length) {
data.sort((item1, item2) =>
item1?.[columnName] > item2?.[columnName] ? -1 : 1 // -1 to update the sequence
);
// return data;
}
};

let arrSortBy = sortBy?.split(" "); //0 -> method, 1 -> columnname
if (!arrSortBy?.length) return data;
else if (arrSortBy[0] === "up") {
ascSort(arrSortBy[1]);
} else if (arrSortBy[0] === "down") {
descSort(arrSortBy[1]);
}
return data;
};

Before rendering the component pass the data through this function it will automatically gives the sorting power to the array of objects.
On changing of sortData state the component will rerender and sortTheData will preprocess the data according to the need.

--

--

No responses yet