Last active
April 12, 2018 09:22
-
-
Save ortonomy/6577017b8d12a5868e206b49fe0509a9 to your computer and use it in GitHub Desktop.
How to pass methods as props to children and grand-children in react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// demo https://codesandbox.io/s/pymqjk7nkj | |
import React, { Component } from 'react'; | |
class One extends Component { | |
constructor(props) { | |
super(props); | |
this.methodOne = this.methodOne.bind(this); | |
this.state = { | |
clicked: false | |
} | |
} | |
methodOne(e) { | |
this.setState({ clicked: true }); | |
} | |
render() { | |
return (<div style={{ padding: '10px', border: '2px solid black', margin: '5px' }}> | |
<p> Clicked status: { this.state.clicked ? 'true' : 'false'} </p> | |
<p> Content of component one </p> | |
<Two method={this.methodOne} /> | |
</div>) | |
} | |
} | |
const Two = ({methodOne, ...props}) => { | |
console.log(props); | |
return ( | |
<div style={{ padding: '10px', border: '2px solid black', margin: '5px' }}> | |
<p> Content of component two </p> | |
<Three passThroughMethod={props.method} /> | |
</div> | |
) | |
} | |
class Three extends Component { | |
constructor(props) { | |
super(props); | |
this.handleClick = this.handleClick.bind(this); | |
} | |
handleClick(e) { | |
this.props.passThroughMethod(); | |
} | |
render() { | |
return ( | |
<div style={{ padding: '10px', border: '2px solid black', margin: '5px' }}> | |
<p> Content of component three </p> | |
<button onClick={this.handleClick}>Click me to demonstrate prop passdown</button> | |
</div> | |
) | |
} | |
} | |
export default One; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment