use-roving-index
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

⌨️ use-roving-index

Manage an active index that needs to be contained or wrapped.

Install

yarn add use-roving-index
npm install use-roving-index

Usage

import React from 'react'
import { useRovingIndex } from 'use-roving-index'

const items = ['Item 1', 'Item 2', 'Item 3']

function App() {
  const {
    activeIndex,
    moveActiveIndex,
    moveBackward,
    moveBackwardDisabled,
    moveForward,
    moveForwardDisabled,
  } = useRovingIndex({ maxIndex: items.length - 1 })
  return (
    <>
      <ul
        tabIndex={0}
        onKeyDown={(event) => {
          const multiplier = event.shiftKey ? 3 : 1
          switch (event.key) {
            case 'ArrowUp':
            case 'ArrowLeft':
              moveActiveIndex(-1 * multiplier)
              break
            case 'ArrowDown':
            case 'ArrowRight':
              moveActiveIndex(1 * multiplier)
              break
          }
        }}
      >
        {items.map((title, index) => (
          <li
            key={title}
            style={{ backgroundColor: index === activeIndex && 'pink' }}
          >
            {title}
          </li>
        ))}
      </ul>
      <button disabled={moveBackwardDisabled} onClick={moveBackward}>
        Previous
      </button>
      <button disabled={moveForwardDisabled} onClick={moveForward}>
        Next
      </button>
    </>
  )
}

Package Sidebar

Install

npm i use-roving-index

Weekly Downloads

34

Version

2.0.0

License

MIT

Unpacked Size

32.7 kB

Total Files

16

Last publish

Collaborators

  • souporserious