Implementing Sorting In A React SPA

When adding the “sorting” functionality to an already created table in an app, the first thing to avoid is “mixing levels of abstraction”. You should avoid mixing the high level and low level components as this reduces symmetry in your code. In my already created app, I’ve extracted the table which will have the sorting functionality from the main component and created a new file and inputted the table in the newly created file. I’ve created a functional component called “Table” and passed in props. I don’t need state and as it’s functional, render isn’t required. The table also has “like” and “delete” buttons with onClick handlers. The event handlers are now changed from “this.handleLike” and “this.handleDelete” to “onLike” and “onDelete” The functions will remain in the main component and will be passed down via props.

import React from "react";const Table = props => {
const { toys, onDelete, onLike } = props
return (
)
}

For each table heading, click and sort events will need to be raised. In the destructured props, I’ve added the reference to the function “onSort”.

import React from "react";const Table = props => {
const { toys, onDelete, onLike, onSort } = props
return (
<table>
<thead>
<tr>
<th onClick={() => onSort ()}>Name</th>
<th onClick={() => onSort ()}>Type</th>
<th onClick={() => onSort ()}>Level</th>
<th onClick={() => onSort ()}>Price</th>
</thead>
</table>
)
}

The sorting event handler will be implemented in the main component and passed down via the “onSort” reference as props.

state = {
sortColumn: {path: "name", order: "asc"}
}
handleSort = path => {
this.setState ({ sortColumn: {path, order: 'asc'}})
}
const sorted = _.orderBy(filtered, [sortColumn.path], [sortColumn.order])

In state, I’ve added a property, “sortColumn” and set it to an object with two properties, path and then order which is set to ascending. I’ve also initialised “sortColumn” in the state, set the path to “name” and the order to ascending. To implement sorting, using lodash, I’ve called the “orderBy” method which takes in the argument of the filtered selection and because the sort function will sort by an individual column, the next argument will be the array “sortColumn.path” and the final argument will be the order “sortColumn.order” after the event handler has been triggered.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store