Last active
June 8, 2017 20:55
-
-
Save garretttaco/a11c1205e30c944634df5da2c9457cfb to your computer and use it in GitHub Desktop.
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
// Separate the container and presentional components | |
import React, { Component } from 'react' | |
// Presentational component is pure. It is only responsible for accepting props and returning JSX. | |
const Child = ({ show, onClickShow, onClickHide }) => ( | |
<div> | |
{show && <span>Now you can see me!</span>} | |
<button onClick={onClickShow}>Show</button> | |
<button onClick={onClickHide}>Hide</button> | |
</div> | |
) | |
// Container component manages state and methods. The container is responsible for rendering the child and passing down props. | |
class Container extends Component { | |
state = { show: false } | |
onClickHide = () => { | |
this.setState({ | |
show: false, | |
}) | |
} | |
onClickShow = () => { | |
this.setState({ | |
show: true, | |
}) | |
} | |
render() { | |
const { show } = this.state | |
return ( | |
<Child | |
show={show} | |
onClickHide={this.onClickHide} | |
onClickShow={this.onClickShow} | |
/> | |
) | |
} | |
} | |
// Alternatively, since this container is so small, why put them in different files or even functions? | |
// The presentational component is not reusable in this case, so we will write it in the same component. | |
// Why? Because why not. There is no reason to separate these here. | |
// Here is how this would look together. | |
import React, { Component } from 'react' | |
class Container extends Component { | |
state = { show: false } | |
onClickHide = () => { | |
this.setState({ | |
show: false, | |
}) | |
} | |
onClickShow = () => { | |
this.setState({ | |
show: true, | |
}) | |
} | |
render() { | |
const { show } = this.state | |
return ( | |
<div> | |
{show && <span>Now you can see me!</span>} | |
<button onClick={this.onClickShow}>Show</button> | |
<button onClick={this.onClickHide}>Hide</button> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment