Skip to content Skip to sidebar Skip to footer

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: Right now I'm getting: TypeError: can't access property 'getAttribute', e is undefined

Solution 1:

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


Solution 2:

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 
}

Solution 3:

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

Post a Comment for "How To Return An Attribute Of Clicked Element In React?"