0

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>
    )
}

}

1
  • this.handleClick should be good enough. No need to bind this since binding occurs automatically of the this keyword when you use arrow functions. Commented Feb 18, 2018 at 2:43

1 Answer 1

1

you need to do it as a function e.g.

<li onClick={() => console.log('li 2 clicked')}>Hello</li>

and because your handleClick function is an arrow function, it is already bound to this so you can just do:

<li onClick={this.handleClick}>Item 1</li>
Sign up to request clarification or add additional context in comments.

3 Comments

is console.log not a function?
@VincentWei it is a function, but you are calling the function within the onClick. You would have to pass console.log without passing an argument, but that would result in the click event being passed in as the argument.
yeah, to add to what @ryandrewjohnson said (which is 100% correct), you are immediately invoking console.log by having () with a parameter, in your case 'li 2 clicked'; if you were to load the page and look at the console, you should see li 2 clicked without actually clicking it (with your version of the code)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.