JAVASCRIPT

Access and Interact with DOM Elements using useRef

Discover how to use React's `useRef` hook to directly access and manipulate DOM elements, such as focusing an input field or interacting with media players.

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

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

  useEffect(() => {
    // Focus the input element when the component mounts
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []); // Empty dependency array ensures this runs once after initial render

  const handleButtonClick = () => {
    if (inputRef.current) {
      inputRef.current.value = 'Hello from button!';
      inputRef.current.focus();
    }
  };

  return (
    <div>
      <input type="text" ref={inputRef} placeholder="I will be focused!" />
      <button onClick={handleButtonClick}>Set Text & Focus</button>
      <p>Use `useRef` to interact directly with the underlying DOM element.</p>
    </div>
  );
}

export default FocusInput;
How it works: This snippet demonstrates the `useRef` hook to directly interact with a DOM element. `inputRef` is created and attached to the input field using the `ref` attribute. In `useEffect`, after the component mounts, `inputRef.current` provides direct access to the actual DOM node, allowing methods like `focus()` to be called. This is useful for scenarios requiring imperative DOM manipulations that aren't easily achieved declaratively.

Need help integrating this into your project?

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

Hire DigitalCodeLabs