Answer the question
In order to leave comments, you need to log in
What is the correct next sort (React)?
Hello. Guys, please tell me how to do the following sorting:
I have some initial data:
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [
{id: 1},
{id: 2},
{id: 3},
{id: 4},
{id: 5},
{id: 6},
{id: 7},
{id: 8},
{id: 9},
{id: 10}
]
};
}
nextHandler = () => {
};
prevHandler = () => {
};
render() {
return (
<React.Fragment>
<ul className="list">
{
this.state.items.map((item) => {
return (
<div
key={item.id}
>
<div className="list__item">
key={item.id}
</div>
</div>
);
})
}
</ul>
<div className="controls">
<button type="button" onClick={this.prevHandler}>prev</button>
<button type="button" onClick={this.nextHandler}>next</button>
</div>
</React.Fragment>
);
}
};
export default App;
this.items = [
{id: 2},
{id: 3},
{id: 4},
{id: 5}
{id: 1},
];
this.state.items = [
{id: 3},
{id: 4},
{id: 5}
{id: 1},
{id: 2}
];
this.state.items = [
{id: 5},
{id: 1},
{id: 2},
{id: 3},
{id: 4}
];
this.state.items = [
{id: 1},
{id: 2},
{id: 3},
{id: 4},
{id: 5}
];
Answer the question
In order to leave comments, you need to log in
nextHandler = () => {
const items = [...this.state.items];
items.push(items.shift());
this.setState({ items });
}
prevHandler = () => {
const items = [...this.state.items];
items.unshift(items.pop());
this.setState({ items });
}
<button onClick={this.nextHandler} data-step={-1}>prev</button>
<button onClick={this.nextHandler} data-step={+1}>next</button>
nextHandler = (e) => {
const step = +e.target.dataset.step;
this.setState(({ items }) => ({
items: [ ...items.slice(step), ...items.slice(0, step) ],
}));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question