-
-
Save ronag/bc8b9a33da172520e123 to your computer and use it in GitHub Desktop.
redux treeview
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
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