Lucas Katayama Lucas Katayama - 1 month ago 4
HTML Question

Inner button onClick event not being fired with React

Hi I have something like this in a React application:

<li onClick={this.props.onToggleTodo}>
Todo
<button onClick={this.props.onRemove}>Remove</button>
<li>


But when I click on remove button... the handler onToggleTodo is fired but onRemove isn't.

I fixed by doing this on handler:

onToggleTodo = t => (e) => {
if(e.target.tagName == 'LI'){
this.setState({done: true});
}
}


It wasn't firing because of setState because it makes React render again...

That is NOT the best way, RIGHT?????

Here is the demo and the code

Answer

It's probably because the onToggleTodo is on the li and the li is a container for the button... You might want to try working as following:

<li>
    <span onClick={this.props.onToggleTodo}>Todo</span>
    <button onClick={this.props.onRemove}>Remove</button>
<li>

edit

If you REALLY want to work the way you were doing at first, I think this should work also:

<li {todoToggled ? onClick={this.props.onToggleTodo}}>
    Todo
    <button  onClick={this.props.onRemove}>Remove</button>
<li>

onToggleTodo = () => {
  this.setState({
    todoToggled = true
  })
  //Rest of your code
}

onRemove = () => {
  this.setState({
    todoToggled = false
  })
  //Rest of your code
}

I'm not 100% if the syntax is correct here because I'm writing this without any feedback, but I think it's headed in the correct direction.

Comments