This is the 13th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Translate: beta.reactjs.org/learn/manip…

Because React already processes the DOM structure based on render’s output, your components won’t need to manipulate the DOM very often. However, there may be times when you need to manipulate DOM elements managed by React, for example, to focus on a node, scroll to the node, or calculate its width and height. React has no built-in method to do this, so you’ll need ref to point to the DOM node.

In this series of articles you will learn:

  • How do I access DOM nodes managed by React using the REF attribute
  • How to integrate JSXrefAttribute associated withuseRefhook
  • How do I access the DOM nodes of other components
  • In which case it is safe to modify the DOM managed by React

For an introduction to and examples of refs, see my previous series of articles, useRef, which is easy to parse

series

How do I manipulate the DOM using ref? (1) Use ref to access DOM node

Example: Input focus

In this case, clicking on the button will focus on input:

import { useRef } from 'react';

export default function Form() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>
        Focus the input
      </button>
    </>
  );
}
Copy the code

To achieve this:

  • withuseRefHook statementinputRef.
  • willinputRefAs a<input ref={inputRef}>Pass.This tells React to put this<input>Into the DOM nodeinputRef.currentIn the.
  • inhandleClickFunction, frominputRef.currentRead the INPUT DOM node and useinputRef.current.focus()For the callfocus().
  • useonClickhandleClickThe event handler passes to<button>.

While DOM operations are the most common use case for refs, useRef hooks can be used to store other things outside of React, such as timer ids. Like state, refs remains constant from rendering to rendering. You can even think of refs as state variables that don’t trigger rerender when you set them

Example: Scroll to an element

You can have multiple references in a component. In this example, there is a rotation of three images and three buttons that are centered in the viewport on the corresponding DOM node by calling the browser scrollIntoView() method:

import { useRef } from 'react';

export default function CatFriends() {
  const firstCatRef = useRef(null);
  const secondCatRef = useRef(null);
  const thirdCatRef = useRef(null);

  function handleScrollToFirstCat() {
    firstCatRef.current.scrollIntoView({
      behavior: 'smooth'.block: 'nearest'.inline: 'center'
    });
  }

  function handleScrollToSecondCat() {
    secondCatRef.current.scrollIntoView({
      behavior: 'smooth'.block: 'nearest'.inline: 'center'
    });
  }

  function handleScrollToThirdCat() {
    thirdCatRef.current.scrollIntoView({
      behavior: 'smooth'.block: 'nearest'.inline: 'center'
    });
  }

  return (
    <>
      <nav>
        <button onClick={handleScrollToFirstCat}>
          Tom
        </button>
        <button onClick={handleScrollToSecondCat}>
          Maru
        </button>
        <button onClick={handleScrollToThirdCat}>
          Jellylorum
        </button>
      </nav>
      <div>
        <ul>
          <li>
            <img
              src="https://placekitten.com/g/200/200"
              alt="Tom"
              ref={firstCatRef}
            />
          </li>
          <li>
            <img
              src="https://placekitten.com/g/300/200"
              alt="Maru"
              ref={secondCatRef}
            />
          </li>
          <li>
            <img
              src="https://placekitten.com/g/250/200"
              alt="Jellylorum"
              ref={thirdCatRef}
            />
          </li>
        </ul>
      </div>
    </>
  );
}
Copy the code