1

I was working on my react project and I put an onClick function and dataset to my <tr> element like this

<tr key={index} onClick={ev} data-ti={ddd.id} className={classs}>

and so in that ev function I tried to get the value from the dataset like this

function ev(e){

    const {ti} = e.target.dataset

   console.log(ti) // returns undefined
}

and instead of returning an id it returns undefined am I doing something wrong or maybe there's another way of doing it

Melly
  • 675
  • 8
  • 24
  • https://stackoverflow.com/a/21664414/1051677 That's one way to do it but I'm surprised `e.target.dataset` doesn't work. – Silviu Burcea Jun 10 '21 at 10:27
  • https://stackoverflow.com/a/10086501/1051677 maybe use `currentTarget` instead? – Silviu Burcea Jun 10 '21 at 10:27
  • `event.target` is the element clicked on, `this` is the element whose handler called the listener, so `let ti = this.dataset.ti` is significantly simper and more efficient. – RobG Jun 10 '21 at 13:10

2 Answers2

2

It's likely that instead of clicking on the tr you're actually clicking on the td inside it. So you need to get the parentNode of that td first, and then grab the data attribute.

const tr = document.querySelector('tr');

tr.addEventListener('click', handleClick, false);

function handleClick(e) {
  const { target: { parentNode } } = e;
  const { dataset: { ti } } = parentNode;
  console.log(ti);
}
<table>
  <tbody>
    <tr data-ti="test">
      <td>Test</td>
    </tr>
  </tbody>
</table>

I'll add Rob's edit here.

const tr = document.querySelector('tr');

tr.addEventListener('click', handleClick, false);

function handleClick(e) {
  const tr = e.target.closest('tr');
  const ti = tr ? tr.dataset.ti : null;
  console.log(ti);
}
<table>
  <tbody>
    <tr data-ti="test">
      <td>Test</td>
    </tr>
  </tbody>
</table>
Andy
  • 61,948
  • 13
  • 68
  • 95
  • 1
    Which presumes that the click is on a td. It might be better to use `let tr = e.target.closest('tr'); let ti = tr? tr.dataset.ti : null;` which is also somewhat more semantic. – RobG Jun 10 '21 at 10:44
  • I do keep forgetting about `closest`. Thanks for the heads-up. @RobG – Andy Jun 10 '21 at 10:50
0

You can simply set the event inside your onClick with a variable of the value you want, like onClick={ev(ddd.id)}.

m4el
  • 455
  • 1
  • 4
  • 14