Created
October 9, 2018 17:09
-
-
Save sagar-gavhane/71c90c66de3dc9d2581df510b9e44af8 to your computer and use it in GitHub Desktop.
React render props pattern
This file contains 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
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