Skip to content

Instantly share code, notes, and snippets.

@ortonomy

ortonomy/propspassing.js

Last active Apr 12, 2018
Embed
What would you like to do?
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
You can’t perform that action at this time.