Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
189
rated 0 times [  194] [ 5]  / answers: 1 / hits: 5308  / 4 Years ago, sun, july 5, 2020, 12:00:00

I was wondering if there is a simple way to get an attribute of clicked element in React.js:




function App () {
return (
<button
title={'foo'}
onClick={myFunction(this)}
>
click me
</button>
)
}

function myFunction(e) {
alert(e.getAttribute('title'));
}




Right now I'm getting: TypeError: can't access property "getAttribute", e is undefined.


I need it inside a function for pass the attribute into another (working) function later on.


More From » reactjs

 Answers
17

You can access the title via currentTarget


try this:



function App () {
return (
<button
title={'foo'}
onClick={myFunction}
>
click me
</button>
)
}

function myFunction(e) {
alert(e.currentTarget.title);
}


[#3280] Thursday, July 2, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminkyrap

Total Points: 631
Total Questions: 89
Total Answers: 109

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;