0

Why does console.log need to wrapped before I can use it in an event handler?

https://jsfiddle.net/7e5yLh63/17/

In the example above, this code does nothing (line 44-51) when I click 'Add':

function ManufacturerWrapper() {
  return <AddManufacturerForm onAddManufacturer={console.log} />
}

But when I change it to

function log(msg) {
  console.log(msg);
}

function ManufacturerWrapper() {
  return <AddManufacturerForm onAddManufacturer={log} />
}

It logs to the console as expected. Why can't I just pass in console.log directly? Why do I need to wrap it in my own function first?

I'm using Firefox if that matters

A G
  • 997
  • 2
  • 18
  • 36
  • I’m not entirely sure, but passing `console.log.bind(console)` should work. If that’s the case, then the reason that `console.log` alone doesn’t work would be: it’s a method that depends on the `this` context. – hackape Dec 30 '20 at 16:26
  • https://stackoverflow.com/questions/28668759/what-does-this-statement-do-console-log-bindconsole – epascarello Dec 30 '20 at 16:27
  • you mean change it to `onAddManufacturer={console.log.bind(console)}`? It doesn't result in printing in the jsfiddle – A G Dec 30 '20 at 17:57

1 Answers1

0

You're probably asking for this:

onAddManufacturer={()=>console.log('log this!')}
tpliakas
  • 1,118
  • 1
  • 9
  • 16
  • 1
    That's another way of writing the same thing the OP has already found to solve the problem, only less efficient since a new function is generated each time the component renders … and it doesn't address the question of *Why*. – Quentin Dec 30 '20 at 17:18