6

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.

3
  • Have you tried e.target.getAttribute? Commented Jul 5, 2020 at 16:32
  • @AnuragSrivastava unfortunately yes, it says: TypeError: Cannot read property 'target' of undefined Commented Jul 5, 2020 at 16:40
  • You don't need to pass this, it doesn't refer to the click event Commented Jul 5, 2020 at 16:42

3 Answers 3

6

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); 
}

Sign up to request clarification or add additional context in comments.

1 Comment

Wow it's too simple :) Thanks so much!
1

You have to call like this

<button
    title={'foo'}
    onClick={(e) => myFunction(e.currentTarget.title)}
>
   click me
</button>

In the function, you have to get like this.

function myFunction(e) {
  alert(e); // e is the value that you have pass 
}

1 Comment

<button> does not have value attribute
1

onClick={myFunction(this)} means that the value of onClick prop will be set to the value that is returned by myFunction, i.e. myFunction(this) is run immediately when the code is evaluated (and not when the button is clicked). You probably want to have something like onClick={() => myFunction(this)} instead, so that the arrow function will be run when the button is clicked (and the arrow function will call myFunction).

However, this is undefined, as seen from the error message you got ("e is undefined"), hence you get the error (undefined doesn't have a property called "getAttribute").

You can pass the event object to myFunction like this:

onClick={(e) => myFunction(e)}

Then you can access the button element with e.currentTarget and then get the title attribute:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.