0

I'm trying to figure out how i can get data attritube and i have search some answer but it's all not working.

<div onClick={handlePropsClick}
     title={'aaa'}
     data-id={2}
>
   <div className='value-text'>Hello</div>
</div>

const handlePropsClick = () => event =>  {
    alert(event.target.getAttribute('data-id'));
};

But I get null and am expecting to get 2 So what's the best way to do this in react

from the suggestion of @Jaromanda X I try to debug and print the value of event.tartfer to console below is what I got

   console.log(event.target) 
    output: <div class="value-text">Hello</div> 
    which is a child element then i do 
console.log(event.target.parentNode) 
output: 
 <div  title="aaa" data-id="2">        
   <div class="value-text">Hello</div>  
</div> 
and then when i do console.log(event.target.parentNode.getAttribute)
sam
  • 853
  • 3
  • 19
  • 50
  • debug step 1: `console.log(event.target)` to see what the target actually is – Jaromanda X Oct 15 '22 at 02:35
  • `console.log(event.target)` gives `
    Hello
    which is a child element then i do `console.log(event.target.parentNode)` which gives `
    Hello
    ` and then when i do `console.log(event.target.parentNode.getAttribute)` i still get null
    – sam Oct 15 '22 at 03:08
  • `event.target.closest('[data-id]')?.dataset.id` — See [`Element.closest()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest) and [`HTMLElement.dataset`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) – jsejcksn Oct 15 '22 at 03:15
  • did you know that `data-xxx` attributes are available using `element.dataset.xxx` - perhaps not your issue, but it's cleaner looking code :p – Jaromanda X Oct 15 '22 at 03:37

0 Answers0