Skip to content

Instantly share code, notes, and snippets.

@seanhess
Created September 14, 2015 15:50
Show Gist options
  • Save seanhess/85e3483f1250f69ae425 to your computer and use it in GitHub Desktop.
Save seanhess/85e3483f1250f69ae425 to your computer and use it in GitHub Desktop.
Stateless React Components
class ParentView extends React.Component {
constructor() {
this.state = {
// parent state becomes child props
items: ["one", "two", "three"]
}
}
// item is a complete domain object with enough info to do things with
onDeleteItem(item) {
this.setState({items: this.state.items.filter(i => i != item)})
}
render() {
var rows = this.state.items.map((item) => {
return <ItemView item={item} onDelete={this.onDeleteItem.bind(this)} />
})
return <div>
<h1>Items</h1>
<div>{rows}</div>
</div>
}
}
// This component is completely stateless
// but it COULD also have some state in it
// there's a separation of the data and actions that come from the parent (props)
// and the child (state)
class ItemView extends React.Component {
onClick() {
// I'm letting the parent handle this action
this.props.onDelete(this.props.item)
}
render() {
return <div>
<label>{this.props.item}</label>
<button onClick={this.onClick.bind(this)}>Delete Me</button>
</div>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment