Roving focus in react with custom hooks

javascript react reacthooks a11y

When you have list you may want to move the focus of between list items using arrow keys to make it more accessible and keyboard friendly. You may also want to wrap the focus back to the top when it reaches bottom. You can achieve this using technique called Roving focus.

The idea is really simple when you want to focus next element in the list you make tabIndex of next element 0 and tabIndex of all other list items -1 and you call ref.current.focus() on the ref of that list item so that element comes into view. We also need to maintain the size of the list and index of the current item that is focused so that we can know what element to focus next.

We can write a simple custom hook that does this

import { useCallback, useState, useEffect } from "react";

function useRoveFocus(size) {
const [currentFocus, setCurrentFocus] = useState(0);

const handleKeyDown = useCallback(
e => {
if (e.keyCode === 40) {
// Down arrow
setCurrentFocus(currentFocus === size - 1 ? 0 : currentFocus + 1);
} else if (e.keyCode === 38) {
// Up arrow
setCurrentFocus(currentFocus === 0 ? size - 1 : currentFocus - 1);
[size, currentFocus, setCurrentFocus]

useEffect(() => {
document.addEventListener("keydown", handleKeyDown, false);
return () => {
document.removeEventListener("keydown", handleKeyDown, false);
}, [handleKeyDown]);

return [currentFocus, setCurrentFocus];

export default useRoveFocus;

We can use this hook as follows

import React from "react";

import Item from "./Item";
import useRoveFocus from "./useRoveFocus";
import characters from "./onePunchManCharacters";

const List = () => {
const [focus, setFocus] = useRoveFocus(characters.length);

return (
{, index) => (
focus={focus === index}

export default List;

Since we may want change the focus when element is clicked we pass setFocus function from the hook to the item to change the focus

import React, { useEffect, useRef, useCallback } from "react";

const Item = ({ character, focus, index, setFocus }) => {
const ref = useRef(null);

useEffect(() => {
if (focus) {
// Move element into view when it is focused
}, [focus]);

const handleSelect = useCallback(() => {
// setting focus to that element when it is selected
}, [character, index, setFocus]);

return (
tabIndex={focus ? 0 : -1}

export default Item;

Here is the repo for the above code and you can find the working sample here

This post is also available on DEV.