How to do Sorting in React

Sorting in React

Many times we have to show the data from the backend in the form of a list or tabular form.
This data helps us find specific information. So there are can be plenty of data that react have to show. Hence it is important that we should be able to sort data in a specific manner based on the property of data.

E.g.: If data consist of name and id as attributes then we should be able to sort data with alphabetical order of name or we can also sort according to the increasing or decreasing value of Id.

SORT Function in ReactJS

In React it is easy to sort things because of the sort function. This sort() function not only sort the array but also sort the array of objects(which is most of the time JSON data). This sort function along with the two comparison parameters that represent the two consecutive objects or data in an array. Both this data and object is compared with the same attribute and then sorted accordingly. Like if we compare a.name and b.name then alphabetically first will come first. But if we compare a.id and b.id then numerically whichever is low will stand first.

Diagramatic representation of sort((a,b)=> b[property] – a[property])

Note: – This sort of Function compares two consecutive data on basis of the same attribute only. Like a.name and b.index would give error as they won’t have a comparison.

EXAMPLE WITH CODE

Create React APP

Npx create-react-app sorting 
cd> sorting 
npm start

Now the react project is ready.

Step  1:- Create the data static or fetch from dummy API.  This will be the data on which we will perform sorting.

const movies = [
  {
    id: 1,
    name: 'Matrix',
    country: 9,
    collection: 300, //in CRs
    releasedOn: 1999,
  },
  {
    id: 2,
    name: 'Tere Nam',
    country: 3,
    collection: 101,
    releasedOn: 2004,
  },
  {
    id: 3,
    name: 'Bahubali',
    country: 4,
    collection: 500,
    releasedOn: 1987,
  },
];

In this case, I have created an array of movies and each movie have 4 property id, name, country, collection and release date.

Step 2: –  Use hooks like useState to store data in states later used to display

const [data, setData] = useState([]);

we will store all the movies in data and will render them in react-dom.

Step 3:-  Display the data using the map function and provide a button at the top to select sortBy.

return (
   <div className="App">
     <select onChange={(e) => setSortType(e.target.value)}> 
       <option value="country">Country</option>
       <option value="collection">Collection</option>
       <option value="releasedOn">Release Date</option>
     </select>

     {data.map(movie => (
       <div key={movie.id} style={{ margin: '30px' }}>
         <div>{`Movie: ${movie.name}`}</div>
         <div>{`Country: ${movie.country}`}</div>
         <div>{`Collection: ${movie.collection}`}</div>
         <div>{`Year of Release: ${movie.releasedOn}`}</div>
       </div>
     ))}
   </div>
 );

Here we create a button that will be used to select the property by which objects have to be sorted. As in the previous step, we saved the movie in data so we were able to use the map function to iterate through the array using a map and displaying each object.

Step 4:-  As the sorting process will be on the page has to auto-reload to display the sorted data hence we use another hook called useEffect (https://codedec.com/tutorials/hooks-in-reactjs/) to reload the page based on the change of sorting type.

useEffect(() => {
 
 }, [sortType]);

Step 5:-  Write the sortArray function inside the useEffect and call the function inside it as it will be auto executed based on the change in sort type.

const sortArray = type => {
      const types = {
        country: 'country',
        collection: 'collection',
        releasedOn: 'releasedOn',
      };
      const sortProperty = types[type];
      const sorted = [...movies].sort((a, b) => b[sortProperty] - a[sortProperty]);
      setData(sorted);
    };

    sortArray(sortType);

here we select the type based on sort type and use the sort function the compares the consecutive data based on the same property and store the changes in data and will be displayed in react-dom.

Combined Code

APP.js

import React, { useState, useEffect } from 'react';
import './App.css';

const movies = [
  {
    id: 1,
    name: 'Matrix',
    country: 9,
    collection: 300, //in CRs
    releasedOn: 1999,
  },
  {
    id: 2,
    name: 'Tere Nam',
    country: 3,
    collection: 101,
    releasedOn: 2004,
  },
  {
    id: 3,
    name: 'Bahubali',
    country: 4,
    collection: 500,
    releasedOn: 1987,
  },
];

function App() {
  const [data, setData] = useState([]);
  const [sortType, setSortType] = useState('albums');

  useEffect(() => {
    const sortArray = type => {
      const types = {
        country: 'country',
        collection: 'collection',
        releasedOn: 'releasedOn',
      };
      const sortProperty = types[type];
      const sorted = [...movies].sort((a, b) => b[sortProperty] - a[sortProperty]);
      setData(sorted);
    };

    sortArray(sortType);
  }, [sortType]); 

  return (
    <div className="App">
      <select onChange={(e) => setSortType(e.target.value)}> 
        <option value="country">Country</option>
        <option value="collection">Collection</option>
        <option value="releasedOn">Release Date</option>
      </select>

      {data.map(movie => (
        <div key={movie.id} style={{ margin: '30px' }}>
          <div>{`Movie: ${movie.name}`}</div>
          <div>{`Country: ${movie.country}`}</div>
          <div>{`Collection: ${movie.collection}`}</div>
          <div>{`Year of Release: ${movie.releasedOn}`}</div>
        </div>
      ))}
    </div>
  );
}

export default App;

the combined code will be like this. This will sort any array passed in.

OUTPUT

Unsorted

 

sorted by collection

sorted by release year

Note: – red box is not part of the site it is used to highlight the array is sorted by the following property.