Reputation: 453
I have this component SingleEmail that I pass props into such as emailSubject, emailFrom, emailDate, emailBody. I am trying to figure out how I can sort ascending and descending for the dates which are in a format like 4/8/2020.
I setup
<Sort by="emailDate">
<div className="IncomingArea">
{this.state.data.map((value, index) => (
<SingleEmail
Subject={value.emailSubject}
From={value.emailFrom}
Date={value.emailDate}
Body={value.emailBody}
/>
))}
</div>
</Sort>
a component named Sort wrapped around my SingleEmail component which is this
// 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);
};
export default Sort;
and basically I am trying to figure out where to go from here to get this to be able to sort by date asc and desc based on the emailDate values. I have two buttons setup on the page with the SingleEmail component so I can add an onClick for both one for asc and one for desc. Just confused on how to get this sort component to supply states or whatever is needed so I can use them to sort with if that makes sense. Any help would be appreciated =] Hopefully this is not too general of a question =p
Upvotes: 1
Views: 1208
Reputation: 62676
I'm not sure why you need the Sort
component when you can just sort the data that you have using the standard Array's sort method.
Note that you need to cast the strings into Dates objects in order to compare them:
data.sort((a, b)=>{return new Date(a.emailDate) - new Date(b.emailDate)})
Here is how your code should look like:
<div className="IncomingArea">
{
this.state.data.sort(
(a, b) => {
return new Date(a.emailDate) - new Date(b.emailDate)
}).map((value, index) => (
<SingleEmail
Subject={value.emailSubject}
From={value.emailFrom}
Date={value.emailDate}
Body={value.emailBody}
/>
))}
</div>
Upvotes: 1