Skip to main content

use-wrapping-index

Useful React Hook for managing a wrapping index for an array of items.

Install

npm i @alexcarpenter/use-wrapping-index
npm i @alexcarpenter/use-wrapping-index

Usage

import useWrappingIndex from "@alexcarpenter/use-wrapping-index";
 
const sampleData = [{ name: "Alex" }, { name: "Stacey" }, { name: "Frankie" }];
 
function App() {
  const {
    activeIndex,
    previousIndex,
    nextIndex,
    moveToPreviousIndex,
    moveToNextIndex,
  } = useWrappingIndex({
    maxIndex: sampleData.length,
  });
 
  return (
    <>
      <p>Active index: {activeIndex}</p>
      <p>Previous index: {previousIndex}</p>
      <p>Next index: {nextIndex}</p>
      <hr />
      <p>Active user: {sampleData[activeIndex].name}</p>
      <p>Previous user: {sampleData[previousIndex].name}</p>
      <p>Next user: {sampleData[nextIndex].name}</p>
      <hr />
      <button onClick={moveToPreviousIndex}>Previous</button>
      <button onClick={moveToNextIndex}>Next</button>
    </>
  );
}
import useWrappingIndex from "@alexcarpenter/use-wrapping-index";
 
const sampleData = [{ name: "Alex" }, { name: "Stacey" }, { name: "Frankie" }];
 
function App() {
  const {
    activeIndex,
    previousIndex,
    nextIndex,
    moveToPreviousIndex,
    moveToNextIndex,
  } = useWrappingIndex({
    maxIndex: sampleData.length,
  });
 
  return (
    <>
      <p>Active index: {activeIndex}</p>
      <p>Previous index: {previousIndex}</p>
      <p>Next index: {nextIndex}</p>
      <hr />
      <p>Active user: {sampleData[activeIndex].name}</p>
      <p>Previous user: {sampleData[previousIndex].name}</p>
      <p>Next user: {sampleData[nextIndex].name}</p>
      <hr />
      <button onClick={moveToPreviousIndex}>Previous</button>
      <button onClick={moveToNextIndex}>Next</button>
    </>
  );
}

View the code on Github.