I'm debugging my code in react and I have an element that isn't behaving as I expected.
<li onClick={console.log('li element clicked')}>Hello</li>
I simply want to detect if a particular element is clicked and I expect when I click this li element, it should log the message "li element clicked" in my console. However, this doesn't seem to be the case. Please help?
Somehow, by using bind(this) fixes my problem, however, I don't fully understand why.
Here's the code sample:
export class InputQuestion extends React.Component{
constructor(props) {
super(props)
this.state = {
value: '',
};
}
handleClick = () => {
console.log('li 1 clicked');
}
render(){
return (
<Container>
<li onClick={this.handleClick.bind(this)}>Hi</li>
<li onClick={console.log('li 2 clicked')}>Hello</li>
</Container>
)
}
}
this.handleClickshould be good enough. No need to bindthissince binding occurs automatically of thethiskeyword when you use arrow functions.