Fairly new to React Js so bear with me...
I'm using onClick in a child component to change the state of a parent component. The parent state is a boolean which, in turn is used to toggle a class on and off on a seperate element from that which was clicked. Something like this:
In Parent.js (relevant code only):
constructor(props) {
super(props);
this.state = {
elementOpen: false;
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
elementOpen: !this.state.bucketListOpen
})
}
render() {
return (
<Child
className = {this.state.elementOpen ? "open" : "closed"}
toggleClassName = {this.handleClick}
/>
)
}
In Child.js (relevant code only):
render() {
return (
<div>
<div className={this.props.className}>Test</div>
<a onClick={this.props.toggleClassName}>Click Me</a>
</div>
)
}
... and this works fine. No problems. The problem arises when I want to move the {this.props.toggleClassName} in the Child component into a handling function (the reason is so that I can fire more than one event on click). In short, it ceases to work.
I've tried creating a method in the Child component and placing the prop inside the method as follows:
handleClassSwitch() {
return this.props.toggleClassName;
}
render() {
return (
<div>
<div className={this.props.className}>Test</div>
<a onClick={this.handleClassSwitch}>Click Me</a>
</div>
)
}
...but sadly it's not working and I'm stumped. Probably really obvious but I'm struggling here. Any help appreciated.