Consider following example
export default function App() {
const newFunction = (valueOne, valueTwo) => {
console.log('valueOne:', valueOne, 'valueTwo:', valueTwo)
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={newFunction.bind(this, 1)}> Bind (single param) </button>
<br />
<button onClick={newFunction.bind(this, 1, 2)}>Bind (two params) </button>
</div>
);
}
Here this React app is having onClick event where newFunction is called on every click of the button element. To pass the parameter .bind() has been used.
Whenever passing two parameters for the newFunction, the output is printing in console as expected. ex: newFunction.bind(this, 1, 2) outputs to => valueOne: 1 valueTwo: 2
Question:
However while passing single parameter newFunction.bind(this, 1) the output was wierd as below,
valueOne: 1
valueTwo: SyntheticBaseEvent {_reactName: "onClick", _targetInst: null, type: "click", nativeEvent: PointerEvent, target: HTMLButtonElement…}
_reactName: "onClick"
_targetInst: null
type: "click"
nativeEvent: PointerEvent
target:
<button> Bind (single param) </button>
currentTarget: null
eventPhase: 3
bubbles: true
cancelable: true
timeStamp: 12358.5
defaultPrevented: false
isTrusted: true
view: Window
detail: 1
screenX: 2017
screenY: 328
clientX: 571
clientY: 97
pageX: 571
pageY: 97
ctrlKey: false
shiftKey: false
altKey: false
metaKey: false
getModifierState: ƒ modifierStateGetter() {}
button: 0
buttons: 0
relatedTarget: null
movementX: 0
movementY: 0
isDefaultPrevented: ƒ functionThatReturnsFalse() {}
isPropagationStopped: ƒ functionThatReturnsFalse() {}
preventDefault: ƒ preventDefault() {}
stopPropagation: ƒ stopPropagation() {}
persist: ƒ persist() {}
isPersistent: ƒ functionThatReturnsTrue() {}
<constructor>: "SyntheticBaseEvent"
Expected output for newFunction.bind(this, 1) should be valueOne: 1 valueTwo: undefined as the second parameter is not present. Instead it’s behaving in a different way.
Codesandbox URL: https://v12ek.csb.app/ (Go to console tab in developer tools to see the output)
>Solution :
the problem here is that if you bind just one argument the second one is the click event
const newFunction = (valueOne, valueTwo) => {
console.log('valueOne:', valueOne, 'valueTwo:', valueTwo)
};
const fakeEvent = {event: 'click'}
newFunction.bind(this, 1, 2)(fakeEvent) //this works
newFunction.bind(this, 1)(fakeEvent)
newFunction.bind(this, 1, undefined)(fakeEvent) //this works