G
G
gsdev992019-03-22 17:44:21
JavaScript
gsdev99, 2019-03-22 17:44:21

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;

When I click on the next button, I need to sort like this:
this.items = [
  {id: 2},
  {id: 3},
  {id: 4},
  {id: 5}
  {id: 1},
];

By clicking on next:
this.state.items = [
  {id: 3},
  {id: 4},
  {id: 5}
  {id: 1},
  {id: 2}
];

And so on, according to the same logic, cyclically:
I.e. after this state:
this.state.items = [
  {id: 5},
  {id: 1},
  {id: 2},
  {id: 3},
  {id: 4}
];

when clicking on next:
this.state.items = [
  {id: 1},
  {id: 2},
  {id: 3},
  {id: 4},
  {id: 5}
];

And the same logic, just in reverse, when you click on prev.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-03-22
@gsdev99

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 });
}

or, you can do with one handler:
<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 question

Ask a Question

731 491 924 answers to any question