R
R
Ratibor Shugaev2021-01-14 19:27:36
React
Ratibor Shugaev, 2021-01-14 19:27:36

How to render array elements one by one on a button in React?

Good day. It became interesting whether it is possible to render elements of an array one by one in React, for example, on the onClick of a button, and how to implement it. Here is a sample code

const array = [
  {
    field: 'first field',
    id: 1
  },
  {
    field: 'second field',
    id: 2
  },
  {
    field: 'third field',
    id: 3
  },
  {
    field: 'fourth field',
    id: 4
  }
];

const SomeComponent = () => (
<>
 {array.map(el => (
    <span key={el.id}>{el.field}</span>
  ))}
<button onClick={handleField}>Next field</button>
</>
);


Is there some easy way or for example a library? Is it possible to make sure that the elements are not overwritten during the next render, that is, it is possible to gradually display the entire array. Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-01-14
@ratibordas

({ items }) => {
  const [ index, setIndex ] = useState(0);

  return (
    <div>
      <button onClick={() => setIndex((index + 1) % items.length)}>next</button>
      <span>{items[index]}</span>
    </div>
  );
}

https://jsfiddle.net/dpt9nkou/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question