On Codepen I made a Complete component with a toggle component with onClick={this.toggleShadow} but the this in toggleShadow() function returns undefined. The pen is Dungeon crawler
Edit: The function is called but this is undefined
On Codepen I made a Complete component with a toggle component with onClick={this.toggleShadow} but the this in toggleShadow() function returns undefined. The pen is Dungeon crawler
Edit: The function is called but this is undefined
do the binding in constructor and see what happens, do like this:this.toggleShadow = this.toggleShadow.bind(this);
I don’t know if you did something to fix this but it’s working now. If I put console.log(“toggle!”) in your toggleShadow function, and click the button, I see “toggle!” logged to the console.
The function is called just that this is undefined
As @abdellah-el-mennani says, you can bind it in the constructor
this.toggleShadow = this.toggleShadow.bind(this);
or you can do -
<ToggleShadow onClick={this.toggleShadow.bind(this)}/>
In es6, you can write
<ToggleShadow onClick={() => (this.toggleShadow)}/>
Thank you I just fixed my pen.