DEV Community

loading...
Cover image for Circuit a list, a useArray hook

Circuit a list, a useArray hook

phalbert profile image hpal ・1 min read

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!

Discussion

pic
Editor guide