Q:

How to sort list of React components based on different properties?

So, this is a code snippet from my frontend.
{store.results.data.map( result =>
  <ResultItem 
    key={result.id}
    title={result.title}
    description={result.description}
    start_date={result.start_date}
    end_date={result.end_date}
    vendor_name={result.vendor.name}
    buyer_name={result.buyer.name}
    preview_file={result.preview_file}
    status={result.status}
  />
)}

Basically, I'm mapping all the data in my Redux store into ResultItems. I want to be able to sort all my ResultItems by different properties like title, description, start_date, end_date, vendor_name, and buyer_name.
Any ideas on how to do that?

A:

I would create a Sort component and wrap  the result items with it like this:
<Sort by='title'>
{store.results.data.map( result =>
  <ResultItem 
    key={result.id}
    title={result.title}
    description={result.description}
    start_date={result.start_date}
    end_date={result.end_date}
    vendor_name={result.vendor.name}
    buyer_name={result.buyer.name}
    preview_file={result.preview_file}
    status={result.status}
  />
)}
</Sort>

// Note: The 'by' prop passed into <Sort> in my example is hardcoded by you can grab it from redux or set it when user selects something from a list. Also you can pass another prop to indicate whether to sort by ascending or descending order etc

Then within the Sort component you can access the array of result items like this React.Children.toArray and use the sort method for arrays and pass the sort method a 'compare' function.
// Sort.js

import React from 'react';

// Compare function needed by the Sort component
const compare =(a, b) => {
    // you can access the relevant property like this a.props[by]
// depending whether you are sorting by tilte or year, you can write a compare function here, 

  }

const Sort= ({children, by})=> {
If (!by) {
// If no 'sort by property' provided, return original list
return children
}
return React.Children.toArray(children).sort(compare)

}

The main advantage with above is that you can use the Sort component anywhere else and you can keep the sorting logic neatly separate from mapping over the initial results. 

