React sample list

  4:34 am  React

<div id="app">
</div>

 

class MyTable extends React.Component {

constructor(props) {
super(props);
this.state = {items: [], sortCol: 1, sortOrder: "asc" };
}

componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(res => res.json())
.then(
(result) => {
this.setState({items: result});
});
}

usort(colN) {
const { items, sortCol, sortOrder } = this.state;
let sortOrderX = "";
if (colN == sortCol) {
if (sortOrder == "asc") {
sortOrderX = "desc";
} else {
sortOrderX = "asc";
}
}

items.sort((a, b) => {
let nameA = "";
let nameB = "";
switch (colN) {
case 0:
nameA = a.userId;
nameB = b.userId;
break;
case 1:
nameA = a.id;
nameB = b.id;
break;
case 2:
nameA = a.title.toUpperCase(); // ignore upper and lowercase
nameB = b.title.toUpperCase(); // ignore upper and lowercase
break;
case 3:
nameA = a.body.toUpperCase(); // ignore upper and lowercase
nameB = b.body.toUpperCase(); // ignore upper and lowercase
break;
}
if (nameA < nameB) {
if (sortOrderX=="asc") {
return -1;
} else {
return 1;
}
}
if (nameA > nameB) {
if (sortOrderX=="asc") {
return 1;
} else {
return -1;
}
}

return 0;
});
this.setState({sortCol: colN, sortOrder: sortOrderX});
}

del(idx) {
const { items } = this.state;
for (let i = 0; i < items.length - 1; i++) {
if (items[i].id == idx) {
items.splice(i, 1);
this.setState({itemCount: items.length });
return;
}
}
}

render() {
const { items } = this.state;
return (
<div>
<h2>JSON Results:</h2>
<table>
<thead>
<tr>
<th>
<a onClick={() => this.usort(0)} className="sort" href="#">USER ID</a>
</th>
<th>
<a onClick={() => this.usort(1)} className="sort" href="#">ID</a>
</th>
<th>
<a onClick={() => this.usort(2)} className="sort" href="#">TITLE</a>
</th>
<th>
<a onClick={() => this.usort(3)} className="sort" href="#">BODY</a>
</th>
<th>
DELETE
</th>
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.id}>
<td>
{item.userId}
</td>
<td>
{item.id}
</td>
<td>
{item.title}
</td>
<td>
{item.body}
</td>
<td>
<button onClick={() => this.del(item.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
}

const root = ReactDOM.createRoot(document.getElementById("app"));
root.render(<MyTable />);

Reply
Share a link to this topic
close

Be the first one to reply