First, the films should be sorted by increasing rating, I did it, but then when you click on the date (date only), it should be sorted by decreasing date. How can this be done? And the second question in my code, decrement and increment work infinitely, but it is necessary that they work only once ( 1 or -1 and that's it).
import React from "react";
class App extends React.Component {
constructor() {
super()
this.state = {
movies: [
{ id: 1, name: "Deadpool", date: 2016, time: 108, genre: 'action', rating: 5 },
{ id: 2, name: "The Avengers", date: 2012, time: 143, genre: 'action', rating: 4 },
{ id: 3, name: "Slayers", date: 2022, time: 88, genre: 'fantasy,comedy', rating: 3 },
]
}
this.state.movies.sort((a,b) => a.rating > b.rating ? 1 : -1);
}
star(i) {
let arr = new Array(i);
return arr.fill("*");
}
remove(index) {
this.state.movies.splice(index, 1);
this.setState({});
}
increment(plus) {
plus.rating = plus.rating 1;
this.setState({});
}
decrement(minus) {
minus.rating = minus.rating - 1;
this.setState({});
}
render() {
return <>
<h1>Cinemas</h1>
<table className="table table-dark table-striped">
<thead>
<tr>
{
Object.keys(this.state.movies[0]).map((elem, ind) => {
return <th key={ind}>{elem}</th>
})
}
<th>stars</th>
</tr>
</thead>
<tbody>
{
this.state.movies.map((elm,index) => {
return <tr>
<td>{elm.id}</td>
<td>
{elm.name}
<button className="btn btn-primary ms-4" onClick={this.remove.bind(this, index)}>del</button>
</td>
<td>{elm.date}</td>
<td>{elm.time}</td>
<td>{elm.genre}</td>
<td>{elm.rating}</td>
<td>
{this.star(elm.rating)}
<button className="btn btn-primary ms-4" onClick={this.increment.bind(this, elm)}>Increment</button>
<button className="btn btn-primary ms-4" onClick={this.decrement.bind(this, elm)}>Decrement</button>
</td>
</tr>
})
}
</tbody>
</table>
</>
}
}
export default App
Thank you.
CodePudding user response:
To be able to sort by date you could use a function like the below one, and call it on click on the date cell, which transformed into a button:
sortByDecreasingDate() {
this.setState({
...this.state,
movies: this.state.movies.sort(
(a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
)
});
}
<thead>
<tr>
{Object.keys(this.state.movies[0]).map((elem, ind) => {
if (elem === "date") {
return (
<th key={ind}>
<button onClick={() => this.sortByDecreasingDate()}>
{elem}
</button>
</th>
);
}
return <th key={ind}>{elem}</th>;
})}
<th>stars</th>
</tr>
</thead>
And if you want the increment/decrement to work only once, you can set a rated
on each item. You make it equal to false
by default, then when you click on increment/decrement, you set it to true
. And you increment/decrement only if it's false
.
I created this Codesandbox out of your component for a working example.