Get an element by ID in React

0
12


Views:
4

  • Set the ref prop on the element.
  • Use the current property to access the element in the useEffect hook.
import  useRef, useEffect  from "react";
import "./styles.css";

export default function App() 
  const ref = useRef(null);

  useEffect(() => 
    //  use document.getElementById()
    const el = document.getElementById("myelement");
    console.log(el);

    // ️use a ref
    const el2 = ref.current;
    console.log(el2);
  , []);

  return (
    <div>
      <h2 ref=ref id="myelement">
        Your Content
      </h2>
    </div>
  );

When we pass a ref prop to an element, eg, React sets the .current property of the ref object to the corresponding DOM node.

To get an element by ID on click event.

import  useRef  from "react";
import "./styles.css";

export default function App() 
  const ref = useRef(null);

  const handleClick = () => 
    // use a ref
    const el2 = ref.current;
    console.log(el2);
  ;

  return (
    <div>
      <h2 ref=ref id="myelement">
        Your Content
      </h2>

      <button onClick=handleClick>Click</button>
    </div>
  );

Let us know if you liked the post. That’s the only way we can improve.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here