Skip to content

Instantly share code, notes, and snippets.

@ronag
Last active September 24, 2015 22:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronag/bc8b9a33da172520e123 to your computer and use it in GitHub Desktop.
Save ronag/bc8b9a33da172520e123 to your computer and use it in GitHub Desktop.
redux treeview
function selectNode(nodes, id) {
const node = nodes[id]
return {
id,
title: 'Loading...',
...node && {
title: node.title,
children: node.children.map((id) => selectNode(nodes, id))
}
}
}
const mapStateToProps = (state) =>
selectNode(state.nodes, 'root')
const mapDispatchToProps = {
load: nodeActions.load,
unload: nodeActions.unload
}
@connect(mapStateToProps, mapDispatchToProps)
class TreeView extends Component {
render() {
return (
<TreeViewNode {...this.props}/>
)
}
}
class TreeViewNode extends Component {
componentWillMount() {
// Fetch data from database which will update the state through a reducer and thus update the props.
this.props.load(this.props.id)
}
componentWillUnmount() {
// Unload to stop listening for changes and removing from state.
this.props.unload(this.props.id)
}
render() {
const { title = 'Loading...', children = [] } = this.props
return (
<div>
<div>{title}</div>
{children.map((child) =>
<TreeViewNode key={child.id} { ...child }
load={this.props.load}
unload={this.props.unload}/>)}
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment