Child:
JavaScript
x
25
25
1
class Plus extends React.Component{
2
constructor(props){
3
super(props)
4
this.handleClick = this.handleClick.bind(this)
5
}
6
7
handleClick(){
8
console.log('It's Working!')
9
this.props.handleButtonChange()
10
}
11
12
render(){
13
return (
14
<div>
15
<i
16
className="fa fa-plus fa-2x"
17
onClick={() => this.handleClick()}
18
></i>
19
</div>
20
);
21
}
22
}
23
24
export default Plus;
25
Parent:
JavaScript
1
18
18
1
class NoteCreation extends React.Component {
2
constructor(props) {
3
super(props);
4
}
5
6
render() {
7
return (
8
<div className="note-creation">
9
<form action="">
10
<Plus handleButtonChange={this.props.handleButtonChange} />
11
</form>
12
</div>
13
);
14
}
15
}
16
17
export default NoteCreation;
18
GrandParent Component:
JavaScript
1
32
32
1
class App extends React.Component {
2
constructor() {
3
super();
4
this.state = {
5
buttonStat : false
6
};
7
this.handleButtonChange = this.handleButtonChange(this);
8
9
}
10
11
handleButtonChange(){
12
this.setState({
13
buttonStat : true
14
})
15
}
16
17
18
render() {
19
20
return (
21
<div className="App">
22
<NoteCreation
23
handleButtonChange={this.handleButtonChange}
24
/>
25
</div>
26
);
27
}
28
}
29
30
export default App;
31
32
I simply want to pass the method handleButtonChange() from grandParent all the way to child (which is a button), as the button is clicked it triggers the click event which fires up this function making changes in grandparent component(i.e. setting button state)
where am i wrong at or this approach is completely wrong I am really new to react.
i am just want to set state in grandParent via child click event.
i keep getting this error TypeError: this.props.handleButtonChange is not a function
would appreciate any help
Advertisement
Answer
You have a typo in your top component
It should be
JavaScript
1
2
1
this.handleButtonChange = this.handleButtonChange.bind(this);
2
and not
JavaScript
1
2
1
this.handleButtonChange = this.handleButtonChange(this);
2
Alternatively you can declare your method like this
JavaScript
1
6
1
handleButtonChange = () => {
2
this.setState({
3
buttonStat : true
4
})
5
}
6
without using bind
at all.