0

I have td in react that has on click event function , the function sends id of td to the backend node.js and the backend will delete that from database here is my problem sometimes e.target.id gets empty enter image description here but the element has id enter image description here when I look in Chrome debugger, why is this happing ?? but sometimes its works fine enter image description here the id is from another Axios.get and mapped in react

<td
  className="deletebutton"
  id={list.id}
  onClick={async (e) => {
    const deleteid = await e.target.id;
    const socket = io(`http://${process.env.REACT_APP_RUN}:3001`, {
      transports: ["websocket", "polling", "flashsocket"]
    });

    await axios.post(
      `http://${process.env.REACT_APP_RUN}:3001/api/delete/single`,
      {
        idDelete: "" + deleteid + ""
      }
    );
    await socket.emit("get date", ip);
  }}
>
  delete
  <i>
    <IconContext.Provider value={{ size: "16px", className: "factor-icons" }}>
      <div>
        <AiFillDelete />
      </div>
    </IconContext.Provider>
  </i>
</td>;

I tried promises but it has the same problem

  • Try `e.currentTarget.id` instead of `e.target.id`, why u used `await` in id ? – Simone Rossaini Apr 17 '23 at 10:23
  • Table cell elements _abused_ as buttons, that is pretty terrible to begin with. You should start by putting an _actual_ `button` in there first of all. – CBroe Apr 17 '23 at 10:39
  • @CBroe Is that your opinion/preferences or ther's some actually rule? – Simone Rossaini Apr 17 '23 at 11:04
  • @SimoneRossaini HTML elements were given specific meanings & purposes for a reason. Accessibility alone will likely be much better, if this used an actual button - those come with "features" such as being focusable to begin with, which when abusing a table cell for this, would have to be explicitly added. – CBroe Apr 17 '23 at 11:10

2 Answers2

0

Do you really need to get the id from the e.target.id?

That's not a recommended way of doing things in Reactjs. The id could be used from the way you have it in the list.id if they are the same.

So you code should look like this instead

...
id={list.id}
onClick={async (e) => {
  const deleteid = list.id;
  ...
}}
...
0

hi thank you @SimoneRossaini it is work with e.currentTarget.id in this case

but what is diffrence between e.target.id and e.currentTarget.id in this case and how sometimes e.target.id works good and sometimes not

  • You can see the answer to [this question](https://stackoverflow.com/questions/10086427/what-is-the-exact-difference-between-currenttarget-property-and-target-property), which is nice and succinct. In short, because events bubble up the DOM in HTML/JS, `target` is the element that fired the event, while `currentTarget` is the element that has the event listener attached. – Jake Apr 18 '23 at 05:53