Peter Jiang Peter Jiang - 22 days ago 9
Javascript Question

Correctly bind a function to Button onClick

This is a React-Bootstrap-Button:

<Button onClick={console.log('Hello')} className="pull-right">Try me</Button>


I want the function to execute everytime a click the button. However, it will execute on pageload. I read somewhere that I should bind the function:

<Button onClick={console.log('Hello').bind(null)} className="pull-right">Try me</Button>


This gives me the error: Uncaught (in promise) TypeError: Cannot read property 'bind' of undefined.

What should I do?

Answer

You are calling log immediately and then trying to bind its return value (which is undefined).

You need to bind the function itself.

You also need to bind it to the console context and not the null context. log cares about the object it is attached to.

onClick={console.log.bind(console, 'Hello')}

Idiomatic React would create the function separately instead of trying to do it inline though:

function myFunction () {

  function handleClick(e) {
    e.preventDefault();
    console.log('Hello');
  }

  return (
    <Button onClick={handleClick} className="pull-right">Try me</Button>

  );
}