JAVASCRIPT

Managing DOM Focus with useRef

Explore how to use React's useRef hook to programmatically manage DOM focus, enabling features like auto-focusing inputs or controlling accessibility within your components.

import React, { useRef, useEffect } from 'react';

function FocusableInput() {
  const inputRef = useRef(null);

  useEffect(() => {
    // Focus the input field when the component mounts
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []); // Empty dependency array means this runs once on mount

  const handleClick = () => {
    if (inputRef.current) {
      inputRef.current.focus();
      inputRef.current.value = 'Focused!';
    }
  };

  return (
    <div>
      <input type="text" ref={inputRef} placeholder="I will be focused" />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
}

// Example usage in a parent component:
// function App() {
//   return (
//     <div>
//       <h1>Demo Focus Control</h1>
//       <FocusableInput />
//     </div>
//   );
// }
How it works: The `useRef` hook allows you to create a mutable ref object whose `.current` property can hold any mutable value. In this snippet, `inputRef` is used to get a direct reference to the DOM input element. The `useEffect` hook then utilizes this reference to call the `.focus()` method on the input when the component first renders, providing immediate user focus. A button click handler further demonstrates programmatically re-focusing the input and modifying its value directly via the ref.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs