JAVASCRIPT

Programmatically Focus Input Fields with useRef

Learn to programmatically control DOM element focus in React using the `useRef` hook, useful for enhancing accessibility and user experience in forms.

import React, { useRef } from 'react';

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

  const handleFocusClick = () => {
    // current property points to the mounted DOM element
    if (inputRef.current) {
      inputRef.current.focus();
      inputRef.current.style.borderColor = 'blue'; // Example: visually indicate focus
    }
  };

  const handleResetClick = () => {
    if (inputRef.current) {
      inputRef.current.value = '';
      inputRef.current.style.borderColor = ''; // Reset border color
    }
  };

  return (
    <div>
      <h2>Focus Input Example</h2>
      <input
        type='text'
        ref={inputRef} // Attach the ref to the input element
        placeholder='Click button to focus me'
        style={{ border: '1px solid gray', padding: '8px' }}
      />
      <br />
      <button onClick={handleFocusClick} style={{ margin: '10px 5px' }}>Focus Input</button>
      <button onClick={handleResetClick} style={{ margin: '10px 5px' }}>Clear & Unfocus</button>
      <p>Use `useRef` to directly interact with DOM elements, like focusing an input.</p>
    </div>
  );
}

export default FocusInput;
How it works: The `useRef` hook provides a way to access and interact with DOM elements directly in React, outside of the declarative rendering cycle. By attaching a ref object (created with `useRef`) to a JSX element's `ref` attribute, you can gain a mutable reference to the underlying DOM node. This snippet demonstrates using `useRef` to programmatically focus an input field, which is useful for improving user experience in forms (e.g., auto-focusing the first input on page load or after a submission).

Need help integrating this into your project?

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

Hire DigitalCodeLabs