I'm using React and React Spring. React spring has a toggle function that essentially maximizes a window on click. It looks like this:
class Projects extends Component {
constructor() {
super()
this.state = {
instructions: true,
data: ''
}
}
handleClick () {
console.log('hello world');
this.setState({
instructions: false
});
console.log(this.state.instructions);
return true;
}
render() {
return (
{this.state.instructions && (
<div className="projects-instructions">
Instructions here
</div>
)}
<Grid
className="projects"
data={data}
keys={d => d.name}
heights={d => d.height}
columns={2}>
{(data, maximized, toggle) => (
<div onClick={()=>{
return data.clicks ? toggle() : false
}}>
</div>
)}
</Grid>
);
}
}
export default Projects;
What I want to do, is hide the instructions on click. I can make this happen by calling handleClick
via, this.handleClick.bind(this)
in my onClick
tag via: onClick={this.handleClick.bind(this)}
. But that means I have to remove the toggle onClick function. So I found that I could call two functions like so:
onClick={()=>{
this.handleClick.bind(this);
return data.clicks ? toggle() : false;
}}
The issue is that this.handleClick.bind(this)
never runs. console.log doesn't even run.
How should I be doing this?
Binding this
to a function does not call the function. It simply specifies what this
refers to when used within that function. Bind to this
in the constructor, and then, in your onClick
event, simply call the function normally (i.e. this.handleClick()
).
class Projects extends Component {
constructor() {
super();
this.state = {
instructions: true,
data: ''
}
//this is where you bind `this` to methods
this.handleClick = this.handleClick.bind(this);
}
handleClick () {
console.log('hello world');
this.setState({
instructions: false
});
console.log(this.state.instructions);
return true;
}
render() {
return (
{this.state.instructions && (
<div className="projects-instructions">
Instructions here
</div>
)}
<Grid
className="projects"
data={data}
keys={d => d.name}
heights={d => d.height}
columns={2}>
{(data, maximized, toggle) => (
<div onClick={()=>{
this.handleClick();
return data.clicks ? toggle() : false
}}>
</div>
)}
</Grid>
);
}
}
export default Projects;