2

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); } 
3
  • can u show us your onClick function? Commented May 7, 2016 at 13:12
  • Sure. I updated my question. Commented May 7, 2016 at 13:15
  • @Boky Create jsfiddle contain css querys. Your demo should be like this image that we test it. Commented May 7, 2016 at 13:22

1 Answer 1

2

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.

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

3 Comments

If you ment <a onClick={this.props.onClick.bind(this, this.props.name)} name={this.props.name} style={{cursor: 'pointer', display: 'block', textAlign: 'center'}}> , now get in cosole log Warning: bind(): React component methods may only be bound to the component instance. See RegistrationPage and TypeError: event.preventDefault is not a function
so based on you onClick function, this way you can change it to onClick: function(name, event) { alert("The name is " + name) }
That did the trick. Of course, so obvious. And I still could not find a problem. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.