onClick
is an attribute that takes a function - under the hood, React, when receiving <some-element onClick={someFunction}/>
, saves someFunction
for later (notice that it doesn't call the function), and then calls the function when the user clicks. Note that you can rewrite this as <some-element onClick={(...args) => someFunction(...args)}/>
, if that makes more sense to you.
Now here's what happens when the user presses on an element where onKeyPress={e => e.key === 'Enter' && this.validate()}
is present:
- The function
e => e.key === 'Enter' && this.validate()
is called
e.key === 'Enter' && this.validate()
is evaluated
e.key === 'Enter'
is evaluated. If it evaluates to true
, then:
this.validate()
is called and evaluated as a boolean
Notice how it is slighly different than when onKeyPress={e => e.key === 'Enter' && this.validate}
is written instead:
- The function
e => e.key === 'Enter' && this.validate
is called
e.key === 'Enter' && this.validate
is evaluated
e.key === 'Enter'
is evaluated. If it evaluates to true
, then:
this.validate
is evaluated as a boolean. If the function exists, it is coerced into the boolean true
, else this.validate
evaluates to undefined
, which is coerced into the boolean false
. Notice how this.validate
did not get called. I'd regard this as a bug, except if you expressively want this behavior to happen.