DEV Community

Cover image for Circuit a list, a useArray hook
hpal
hpal

Posted on

2 2

Circuit a list, a useArray hook

So recently I had to create a react component that cycles through a list using two arrows. The catch here is the next arrow must go back to the first index after reaching the end and the previous arrow must go to the first item when it reaches the last item.

This being react and using hooks gave me the following result

// useArrayNavigator.js
import { useState } from 'react';

export function useArrayNavigator(arrayLength) {
  const [currentIndex, setCurrentIndex] = useState(0);

  const previousIndex = () => {
    const index = currentIndex === 0 ? arrayLength - 1 : currentIndex - 1;
    setCurrentIndex(index);
  };

  const nextIndex = () => {
    const index = currentIndex === arrayLength - 1 ? 0 : currentIndex + 1;
    setCurrentIndex(index);
  };

  return { currentIndex, previousIndex, nextIndex };
}
Enter fullscreen mode Exit fullscreen mode

To use it in the component:

// widget.js
const Widget = ({ array }) => {
  const { currentIndex, nextIndex, previousIndex } = useArrayNavigator(array.length);

  return (
    <div>
      <span className="text-lg">Top in {array[currentIndex].label}</span>
      <span>
        <button onClick={previousIndex} />
        <button onClick={nextIndex} />
      </span>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

And the result is:
useArray

Notice how I can go through the list continuously.

Till next time!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay