30
loading...
This website collects cookies to deliver better user experience
const transactions = [
{
"id": 1,
"date": "2019-12-01",
"category": "Income",
"amount": 1000
},
{
"id": 2,
"date": "2019-12-02",
"category": "Transportation",
"amount": -10.55
},
{
"id": 3,
"date": "2019-12-04",
"category": "Fashion",
"amount": -24.99
},
{
"id": 4,
"date": "2019-12-06",
"category": "Food",
"amount": 8.75
},
{
"id": 5,
"date": "2019-12-06",
"category": "Housing",
"amount": -17.59
}
]
<table>
like so (don't forget to add a key prop when iterating over an array with the .map()
method):function App() {
return (
<table>
<tbody>
<tr>
<th>
<h3>Date</h3>
</th>
<th>
<h3>Category</h3>
</th>
<th>
<h3>Amount</h3>
</th>
</tr>
{transactions.map(transaction => {
return (
<tr key={transaction.id}>
<td>{transaction.date}</td>
<td>{transaction.category}</td>
<td>{transaction.amount}</td>
</tr>
)})}
</tbody>
</table>
);
}
function App() {
function onHeaderClick(e) {
let type = e.target.textContent.toLowerCase();
const sorted = [...transactions].sort((a, b) => (a[type] > b[type]) ? 1 : ((b[type] > a[type]) ? -1 : 0))
}
return (
<table>
<tbody>
<tr>
<th>
<h3>Date</h3>
</th>
<th>
<h3 onClick={onHeaderClick}>Category</h3>
</th>
<th>
<h3>Amount</h3>
</th>
</tr>
{transactions.map(transaction => {
return (
<tr key={transaction.id}>
<td>{transaction.date}</td>
<td>{transaction.category}</td>
<td>{transaction.amount}</td>
</tr>
)})}
</tbody>
</table>
);
}
.sort()
method mutates the array, we use the spread operator to copy the array of objects over because we never want to directly mutate state. import { useState } from "react";
function App() {
const [ transactions, setTransactions ] = useState([
{
"id": 1,
"date": "2019-12-01",
"category": "Income",
"amount": 1000
},
{
"id": 2,
"date": "2019-12-02",
"category": "Transportation",
"amount": -10.55
},
{
"id": 3,
"date": "2019-12-04",
"category": "Fashion",
"amount": -24.99
},
{
"id": 4,
"date": "2019-12-06",
"category": "Food",
"amount": 8.75
},
{
"id": 5,
"date": "2019-12-06",
"category": "Housing",
"amount": -17.59
}
]);
function onHeaderClick(e) {
let type = e.target.textContent.toLowerCase();
const sorted = [...transactions].sort((a, b) => (a[type] > b[type]) ? 1 : ((b[type] > a[type]) ? -1 : 0))
}
return (
<table>
<tbody>
<tr>
<th>
<h3>Date</h3>
</th>
<th>
<h3 onClick={onHeaderClick}>Category</h3>
</th>
<th>
<h3>Amount</h3>
</th>
</tr>
{transactions.map(transaction => {
return (
<tr key={transaction.id}>
<td>{transaction.date}</td>
<td>{transaction.category}</td>
<td>{transaction.amount}</td>
</tr>
)})}
</tbody>
</table>
);
}
export default App;
function onHeaderClick(e) {
let type = e.target.textContent.toLowerCase();
const sorted = [...transactions].sort((a, b) => (a[type] > b[type]) ? 1 : ((b[type] > a[type]) ? -1 : 0))
setTransactions(sorted);
}