Last active
February 10, 2016 11:11
-
-
Save timdorr/7210fc153e21d11b4792 to your computer and use it in GitHub Desktop.
Reduce some boilerplate around React state
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 Foo extends Component { | |
constructor(props, context) { | |
super(props, context) | |
this.state = { | |
show: false | |
} | |
} | |
handleClick = () => { | |
this.setState({ show: true }) | |
} | |
render() { | |
const { show } = this.state | |
return ( | |
<div> | |
<Button onClick={this.handleClick}>Show More</Button> | |
<Accordion show={show} /> | |
</div> | |
) | |
} | |
} |
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 Bar extends Component { | |
render() { | |
const { show } = this.state || { show: false } | |
return ( | |
<div> | |
<Button onClick={() => this.setState({ show: true }))}>Show More</Button> | |
<Accordion show={show} /> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const { show = false } = this.state || {}
ratheralso, using arrow functions as event handlers creates a new function every time so if
Button
uses pure render mixin or decorator it will re-render unnecessarily