Skip to content

dcooney/react-use-arrows

Repository files navigation

react-use-arrows

A React hook for traversing DOM elements with keyboard arrow keys.

npm

Install

# With npm
npm i react-use-arrows

# With Yarn
yarn add react-use-arrows

Usage

import React from 'react'
import useArrows from 'react-use-arrows'

export default function App() {
   const menuRef = useArrows();

   // Typescript.
   // const menuRef = useArrows() as React.RefObject<HTMLDivElement>

   return (
      <div ref={menuRef}>
         <ul>
            <li>
               <a href="https://github.com/">Github</a>
            </li>
            <li>
               <a href="https://npmjs.com/">NPM</a>
            </li>
            <li>
               <a href="https://react.dev/">React</a>
            </li>
         </ul>
      </div>
   )
}

Options

The useArrows hook accepts an optional object parameter which is a collection of configuration props.

Prop Description Default Type
selectors DOM element selectors that should receive focus. List Array|String
useTab Allow Tab key to navigate focusable elements. true Boolean
useUpDown Up and down arrows navigate focusable elements. true Boolean
useLeftRight Left and right arrows navigate focusable elements. false Boolean
loop Loop through focusable elements. true Boolean
const ref = useArrowControls( { 
   selectors: 'span[role="button"]',
   useTab: false,
});