Home > database >  Selecting parent container id on Click
Selecting parent container id on Click

Time:10-18

I was wondering if it be possible to always select the parent's Id when clicking anywhere on the entire div?

I've made a sample example giving each child divs a different id and console.logging which element id is being selected depending on which part of the entire div you click on.

As said above I just want to be able to always select the parent div's Id, which in this case is "1" no matter which part of the entire div I click on.

function App() {
  function onClick(e) {
    console.log(e.target.id);
  }

  return (
    <div id="1" className="container" onClick={onClick}>
      Decor
      <div id="2" className="img-container">
        <img
          id="3"
          src="https://images.pexels.com/photos/7828323/pexels-photo-7828323.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"
          className="img"
          alt=""
        />
      </div>
      <p id="4">Lorem ipsum</p>
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById("root")
);
body {
  font-family: sans-serif;
  text-align: center;
  display: flex;
  justify-content: center;
}

.container {
  height: 300px;
  width: 200px;
  border: solid green;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.img-container {
  width: 200px;
  height: 200px;
}

img {
  width: 100%;
  height: 100%;
}
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

<div id="root"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Search for the closest ancestor with the "container" class.

function Example() {

  function onClick(e) {
    const { id } = e.target.closest('.container');
    console.log(id);
  }

  return (
    <div id="1" className="container" onClick={onClick}>
      Decor
      <div id="2" className="img-container">
        <img
          id="3"
          src="https://images.pexels.com/photos/7828323/pexels-photo-7828323.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"
          className="img"
          alt=""
        />
      </div>
      <p id="4">Lorem ipsum</p>
    </div>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related