Search code examples
javascriptreactjstic-tac-toe

ReactJS Tic Tac Toe - Different Way to write OnClick Event with This


Ref to ReactJS tutorial. https://reactjs.org/tutorial/tutorial.html#setup-option-2-local-development-environment

<button className="square" onClick={()=>alert('u clicked' + this)}>

The code above is working fine. However, when i had made the changes.

button className="square" onClick={function() {alert('u clicked: ' + this)}}>

the code above is not working.

Based on the explanation from (https://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/), THIS will be auto binded. How can we manual bind for second code?


Next modification i had made

<button className="square" onClick={alert('u clicked' + this)}>

THIS is shown, but it was called, during load. Why?

Thanks in advance.


Solution

  • In the first example, <button className="square" onClick={()=>alert('u clicked' + this)}>, the onClick prop is assigned an arrow function, in which this refers to the context in which the button is created.

    To bind this in the same way for the second example, follow the function definition with .bind(this):

    <button className="square" onClick={function() {alert('u clicked: ' + this)}.bind(this)}>
    

    Your last modification assigns alert('u clicked' + this)'s return value to the onClick property.