Skip to content

Instantly share code, notes, and snippets.

@sagar-gavhane
Created October 9, 2018 17:09
Show Gist options
  • Save sagar-gavhane/71c90c66de3dc9d2581df510b9e44af8 to your computer and use it in GitHub Desktop.
Save sagar-gavhane/71c90c66de3dc9d2581df510b9e44af8 to your computer and use it in GitHub Desktop.
React render props pattern
class App extends Component {
render() {
return (
<React.Fragment>
<h1>Currency Converter</h1>
<Amount
render={data => {
return (
<React.Fragment>
<Euro amount={data.amount} />
<Pound amount={data.amount} />
</React.Fragment>
);
}}
/>
</React.Fragment>
);
}
}
class Amount extends Component {
constructor(props) {
super(props);
this.state = {
amount: 0
};
}
onIncrement = () => {
this.setState(state => ({ amount: state.amount + 1 }));
};
onDecrement = () => {
this.setState(state => ({ amount: state.amount - 1 }));
};
render() {
return (
<div>
<span>US Dollar: {this.state.amount} </span>
<button type="button" onClick={this.onIncrement}>
+
</button>
<button type="button" onClick={this.onDecrement}>
-
</button>
{this.props.render(this.state)}
</div>
);
}
}
const Euro = ({ amount }) => <p>Euro: {amount * 0.86}</p>;
const Pound = ({ amount }) => <p>Pound: {amount * 0.76}</p>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment