Home > OS >  How to get the id of the parent element at different levels of React
How to get the id of the parent element at different levels of React

Time:09-11

I want to access the id of the div element, for this I use parentElement twice and I think it is not a good thing and I am looking for a better way because if the div element is at higher levels, I have to use parentElement several times, which apparently is not the right thing to do. Can you guide me in a better way to access any element I want at any level?

https://codesandbox.io/s/sharp-dijkstra-4yw07r?file=/src/App.js:0-377

export default function App() {
  function handleGetId(e) {
    console.log(e.target.parentElement.parentElement.id);
  }

  return (
    <div style={{ textAlign: "center" }} id="1">
      <div>
        <h1>Hello</h1>
        <h2>The output is in the console</h2>
      </div>
      <div>
        <button onClick={handleGetId}>Click Me !</button>
      </div>
    </div>
  );
}

CodePudding user response:

You can rely on useRef hook and add a ref={...} attribute to the element you want.

import { useRef } from "react";

export default function App() {
  const itemWithIdRef = useRef(null);

  function handleGetId(e) {
    console.log(itemWithIdRef.current.id);
  }

  return (
    <div ref={itemWithIdRef} style={{ textAlign: "center" }} id="1">
      <div>
        <h1>Hello</h1>
        <h2>The output is in the console</h2>
      </div>
      <div>
        <button onClick={handleGetId}>Click Me !</button>
      </div>
    </div>
  );
}

But the purpose of that code is questionable. You can just use

onClick={() => handleGetId(1)}

for example, and just pass the id you want as a parameter. Or pass a state variable in same way.

  • Related