user13084463
user13084463

Reputation:

How to return an attribute of clicked element in react?

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.

Upvotes: 6

Views: 7839

Answers (3)

Matias Kinnunen
Matias Kinnunen

Reputation: 8540

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

Upvotes: 1

Jay Parmar
Jay Parmar

Reputation: 378

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 
}

Upvotes: 1

Marik Ishtar
Marik Ishtar

Reputation: 3049

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

Upvotes: 6

Related Questions