DEV Community

Helder Burato Berto
Helder Burato Berto

Posted on • Originally published at helderberto.com

Manipulating the DOM with React Ref

When you found something like document.querySelector('.something') in your React codebase, it's probably a code smell.

To manipulate the DOM you should consider using "ref" - React Docs - ref

After rendering the DOM element, it will enable the DOM node and its methods to be called.

To ensure the "inputRef.current" will be available at the moment of the trigger "focus()", you can do an "early return" to bail out the effect early, like the following snippet:

import React from "react";

export default function App() {
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (!inputRef.current) {
      return;
    }

    inputRef.current.focus();
  }, [])

  return <input ref={inputRef} type="text" />;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)