Skip to content

Instantly share code, notes, and snippets.

@timdorr
Last active February 10, 2016 11:11
Show Gist options
  • Save timdorr/7210fc153e21d11b4792 to your computer and use it in GitHub Desktop.
Save timdorr/7210fc153e21d11b4792 to your computer and use it in GitHub Desktop.
Reduce some boilerplate around React state
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>
)
}
}
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>
)
}
}
@romseguy
Copy link

romseguy commented Feb 5, 2016

const { show = false } = this.state || {} rather

also, 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment