Blog>
Snippets

Managing Focus Flow with useRef

Create a series of input fields with refs and use these refs to control the flow of focus, such as implementing custom navigation between inputs with arrow keys.
import React, { useRef } from 'react';

function CustomInputNavigation() {
  // Create refs for the input fields
  const firstInputRef = useRef(null);
  const secondInputRef = useRef(null);
  const thirdInputRef = useRef(null);

  // Function to handle key press events
  const handleKeyPress = (event, inputRef) => {
    if (event.key === 'ArrowRight') {
      // Focus the next input on arrow right
      if (inputRef.current.nextElementSibling) {
        inputRef.current.nextElementSibling.focus();
      }
    } else if (event.key === 'ArrowLeft') {
      // Focus the previous input on arrow left
      if (inputRef.current.previousElementSibling) {
        inputRef.current.previousElementSibling.focus();
      }
    }
  };

  return (
    <div>
      <input ref={firstInputRef} onKeyDown={(event) => handleKeyPress(event, firstInputRef)} />
      <input ref={secondInputRef} onKeyDown={(event) => handleKeyPress(event, secondInputRef)} />
      <input ref={thirdInputRef} onKeyDown={(event) => handleKeyPress(event, thirdInputRef)} />
    </div>
  );
}

export default CustomInputNavigation;
This React component creates three input fields, each with a ref associated. An onKeyDown event listener is attached to each input field to handle the arrow key navigation. The handleKeyPress function takes the event and a reference to the input field as parameters. If the user presses the right arrow key, the focus moves to the next input field if it exists. Similarly, if the left arrow key is pressed, the focus moves to the previous input field if available. The refs are used to directly manipulate the DOM elements and control the navigation flow.