Boky
Boky

Reputation: 12084

OnClick event in React

I have one very strange problem.

I have the following link in react

<a onClick={this.props.onClick} name={this.props.name} style={{cursor: 'pointer', display: 'block', textAlign: 'center'}}>
       <span className="regHeaderText">{this.props.value}</span>
       <FontAwesome name={this.props.icon} className="faIcon"/>
</a>

And it's looks like :

enter image description here

But the problem is if I click on text NEXT or on font awesome icon I get undefined as name of the link .

Only if I click somewhere left of text NEXT, in this yellow box only then I get right name.

If I create links instead spans, like :

<a onClick={this.props.onClick} name={this.props.name} style={{cursor: 'pointer', display: 'block', textAlign: 'center'}}>
     <a onClick={this.props.onClick} name={this.props.name} className="regHeaderText">{this.props.value}</a>
     <a onClick={this.props.onClick} name={this.props.name}><FontAwesome name={this.props.icon} className="faIcon"/></a>
</a>

Then it works, but is there any solution to do it without creating links inside link?

EDIT

onClick: function (event) {
    event.preventDefault();
    var field = event.target.name;
    alert("The name is : " + field);
}

Upvotes: 2

Views: 3185

Answers (1)

Christiaan
Christiaan

Reputation: 848

You are probably using e.target in your onClick handler. When you click on the span the event bubbles up to the handler on the link but the target will be the span and not the a.

To circumvent this you can create a bound onClick with the name of the link

<a onClick={this.props.onClick.bind(this, this.props.name)}

The first argument to your onClick method will be the name and the second the event.

Upvotes: 2

Related Questions