Skip to content

Instantly share code, notes, and snippets.

@ortonomy
Last active April 12, 2018 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ortonomy/6577017b8d12a5868e206b49fe0509a9 to your computer and use it in GitHub Desktop.
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
// 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