Iterate over an array. In Style ๐Ÿ˜Ž

Iterate over an array. In Style ๐Ÿ˜Ž

Usecase : Iterating over static array values on a button click , reaching the end and starting over from the beginning.

ยท

1 min read

Let's say you have an array and you want to iterate over the items and whilst reaching the end, on the next button click you want to start from the beginning repeating the same process infinitely.

You can achieve this by using the modulo (%) operator. So how can we do this

import React, { useState } from "react";

function App() {
  let list = ["๐Ÿฅš", "๐Ÿฃ", "๐Ÿ”", "๐Ÿ—", "๐Ÿ’ฉ"];
  const [initialV, setInitiallV] = useState(0);

  const iterateForward = (idx, array) => {
    return (idx = (idx + 1) % array.length);
  };

  const iterateBackward = (idx, array) => {
    return (idx = (idx - 1 + array.length) % array.length);
  };

  const reset = () => {
    setInitiallV(0);
    return;
  };

  return (
    <>
      <div>
        <button onClick={() => setInitiallV(iterateForward(initialV, list))}>
          Next Item
        </button>
        <br />
        <p>{list[initialV]}</p>
        <button onClick={() => setInitiallV(iterateBackward(initialV, list))}>
          Prev Item
        </button>
        <br />
      </div>
      <br />
      <div>
        <button onClick={() => reset()}>Reset</button>
      </div>
    </>
  );
}

export default App;

The final output will look something like

Imagine something like an array consisting of music links, we can use this method to iterate forward and backward at any point.

ย