So i am trying to get a data attribute of a div element but it is giving a null but not always; after like ten times of showing a null, it shows the attribute so what am i missing? is it a bug?
import { useEffect, useState } from 'react';
import './App.css';
function App() {
const [toggleComments, setToggleComments] = useState(false);
const changetoggleState = (e)=> { setToggleComments(toggleComments ? false : true);
console.log(toggleComments); console.log(e.target.getAttribute('data-comment-data'))};
return <div data-comment-data="hello there" onClick={changetoggleState}>Hello World</div>
};
export default App;
CodePudding user response:
Change your code to:
e.target.getAttribute("data-comment-data")
Online demo: https://codesandbox.io/s/spring-paper-dsd1tt?file=/src/App.js:305-347
CodePudding user response:
So the problem was i put the data attribute on the div but when i was clicking for some reason i was clicking on a PNG icon inside the div that did not have any data attribute. that is why it sometimes worked when i did not click on the PNG.