Skip to content

Commit dbb0fb7

Browse files
added new methods to sort by columns
1 parent 3d9a266 commit dbb0fb7

File tree

1 file changed

+62
-16
lines changed

1 file changed

+62
-16
lines changed

src/App.js

Lines changed: 62 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,69 @@
1-
import logo from './logo.svg';
2-
import './App.css';
1+
import React, { useState } from "react";
2+
import "./App.css";
3+
import Articles from "./components/Articles";
4+
5+
const title = "React Sorting articles";
6+
7+
function App({ articles }) {
8+
const [articlesList, setArticlesList] = useState(articles);
9+
10+
const sortByUpvotes = () => {
11+
var newArticles = [];
12+
Object.assign(newArticles, articlesList);
13+
newArticles.sort((a, b) => {
14+
if (a.upvotes > b.upvotes) {
15+
return -1;
16+
}
17+
if (a.upvotes < b.upvotes) {
18+
return 1;
19+
}
20+
return 0;
21+
});
22+
23+
setArticlesList(newArticles);
24+
};
25+
26+
const sortByDates = () => {
27+
var newArticles = [];
28+
Object.assign(newArticles, articlesList);
29+
newArticles.sort((a, b) => {
30+
const aDate = new Date(a.date);
31+
const bDate = new Date(b.date);
32+
if (aDate > bDate) {
33+
return -1;
34+
}
35+
if (aDate < bDate) {
36+
return 1;
37+
}
38+
return 0;
39+
});
40+
41+
setArticlesList(newArticles);
42+
};
343

4-
function App() {
544
return (
645
<div className="App">
7-
<header className="App-header">
8-
<img src={logo} className="App-logo" alt="logo" />
9-
<p>
10-
Edit <code>src/App.js</code> and save to reload.
11-
</p>
12-
<a
13-
className="App-link"
14-
href="https://reactjs.org"
15-
target="_blank"
16-
rel="noopener noreferrer"
46+
<h1> {title} </h1>
47+
<div className="layout-row align-items-center justify-content-center my-20 navigation">
48+
<label className="form-hint mb-0 text-uppercase font-weight-light">
49+
Sort By
50+
</label>
51+
<button
52+
data-testid="most-upvoted-link"
53+
className="small"
54+
onClick={() => sortByUpvotes()}
55+
>
56+
Most Upvoted
57+
</button>
58+
<button
59+
data-testid="most-recent-link"
60+
className="small"
61+
onClick={() => sortByDates()}
1762
>
18-
Learn React
19-
</a>
20-
</header>
63+
Most Recent
64+
</button>
65+
</div>
66+
<Articles articles={articlesList} />
2167
</div>
2268
);
2369
}

0 commit comments

Comments
 (0)