I have a basic articles sorting application, the App component gets some articles and pass them to the Articles component which renders a list of the articles sorted by date or by upvotes.
Each article is an object with id (string), title (string), upvotes (number), and date (string format YYYY-MM-DD) properties.
By default the articles are shown by upvotes in descending order.
This is the Articles component:
import React from "react";
function Articles({ articles }) {
return (
<div>
<table>
<thead>
<tr>
<th>Title</th>
<th>Upvotes</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{articles.map(({id, title, upvotes, date}) => (
<tr key={id}>
<td>{title}</td>
<td>{upvotes}</td>
<td>{date}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default Articles;
And this is the App component:
import React, { useState } from 'react';
import './App.css';
import Articles from './components/Articles';
function App({ articles }) {
const sortByUpvotesDesc = (a,b) => b.upvotes - a.upvotes
const sortByDateDesc = (a,b) => b.date > a.date ? 1 : b.date === a.date ? 0 : -1
const [articlesOrder, setArticlesOrder] = useState('byUpvotesDesc')
const mostUpvotedClickHandler = () => {
setArticlesOrder('byUpvotesDesc')
}
const mostRecentClickHandler = () => {
setArticlesOrder('byDatesDesc')
}
return (
<div className="App">
<div>
<label>Sort By</label>
<button onClick={mostUpvotedClickHandler} >Most Upvoted</button>
<button onClick={mostRecentClickHandler} >Most Recent</button>
</div>
<Articles articles={articles.sort(articlesOrder === 'byUpvotesDesc' ? sortByUpvotesDesc : sortByDateDesc)} />
</div>
);
}
export default App;
I would appreciate any insights and feedback on how to improve this, especially regarding the App component.