Amine
Amine

Reputation: 172

React onClick event on link

I have this weird thing i have this simple component

import React, {Component} from 'react';
const Logo = ({onClick}) => {
return (

    <a name="home" onClick={onClick} className="logo">

        <span className="logo-mini"></span>



    </a>

);
};


export default Logo;

the onClick event suppose to to get the click event on the link to get attribute name but what i got is undefined when i console.log the event.target the out put is <span class="logo-lg"></span>

in the root compenent my render methode call <Logo onClick={this.handleClick}/> handleClick method

    handleClick(){
    let to = event.target.name;
    console.log(event.target);
    }

Upvotes: 1

Views: 19569

Answers (2)

Piotr Berebecki
Piotr Berebecki

Reputation: 7468

You can access the desired attribute by chaining parentElement with the getAttribute() method. Try this in you handleClick method

console.log(event.target.parentElement.getAttribute('name'));

More info here:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute https://developer.mozilla.org/en/docs/Web/API/Node/parentElement


Alternatively, you could use:
console.log(event.target.getAttribute('name')); but this would require that you put the name attribute on your span element.

Also, in case the gist gets deleted, here is a full working code:

class Header extends React.Component { 
  handleClick(event) {
    console.log(event.target.parentElement.getAttribute('name'));
  }
  render() {
    return (
      <Logo onClick={this.handleClick}/>
    );
  }
}

const Logo = ({onClick}) => {
  return (
    <a name="home" onClick={onClick} className="logo">
        <span className="logo-mini">Logo</span>
    </a>
  );
};

ReactDOM.render(<Header/>, document.getElementById('app'));

Link to codepen: http://codepen.io/PiotrBerebecki/pen/LRRYRq

Upvotes: 3

Harkirat Saluja
Harkirat Saluja

Reputation: 8114

You need to bind this to your function call.

 <Logo onClick={this.handleClick.bind(this)}/>

Upvotes: 0

Related Questions