React Setting State Inside Of A Function
I am using some d3 for visualization and decided to also use reactstrap. Basically clicking a circle in d3 will result in the reactstrap element Collapse to appear. I am not findi
Solution 1:
You won’t get this context inside the regular function unless you bind this to the function or change it to arrow function
So, Change
function click2(d) {
this.setState({ collapse: !this.state.collapse });
alert("You clicked on more!" + d.data.name);
}
To
const click2 = d => {
this.setState({ collapse: !this.state.collapse });
alert("You clicked on more!" + d.data.name);
}
Or bind it manually
function click2(d) {
this.setState({ collapse: !this.state.collapse });
alert("You clicked on more!" + d.data.name);
}.bind(this)
Or move the function outside componentDidMount and do manual binding in constructor as
this.click2 = this.click2.bind(this);
Post a Comment for "React Setting State Inside Of A Function"