Last active
January 9, 2016 12:51
stateless function identity in React.js
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
import React from 'react'; | |
import * as ReactDOM from 'react-dom'; | |
var root = { | |
name: 'World', | |
children: [ | |
{name: 'Sun', id:1}, | |
{ | |
name: 'Earth', id:2, | |
children: [ | |
{name: 'Moon', id:3}, | |
{name: 'ISS', id:4}, | |
] | |
}, | |
] | |
}; | |
var foo = ({node, children}) => (<li>{node.name}<ul>{children}</ul></li>); | |
// function that returns stateless React component (i.e. just function) | |
// something like factory design pattern | |
function createRenderer() { | |
// ****** HERE *************************************** | |
return ({node, children}) => (<li>{node.name}<ul>{children}</ul></li>); // comment this and it will be okay | |
return foo; // comment line above to execute this | |
// *** ** **** ****** **** | |
} | |
// represents node in tree | |
class Node extends React.Component { | |
constructor(props) { | |
console.log('node constructor'); | |
super(props); | |
this.state = {node: props.node}; | |
} | |
componentDidMount() { console.log('node did mount');} | |
componentWillUnmount() {console.log('node will unmount')} | |
render() { | |
console.log("node render"); | |
var node = this.state.node; | |
// calculate children markup | |
var children = (node.children || []).map( ch => <Node key={ch.id} node={ch} />); | |
var Renderer = createRenderer(node, children); | |
return <Renderer node={node} children={children} /> | |
} | |
} | |
var instance = ReactDOM.render( | |
<Node node={root} />, | |
document.getElementById('container') | |
); | |
setTimeout( () => { | |
// state mutation | |
root.children[0].name = 'Black Hole'; | |
// update | |
instance.setState({node: root}); | |
}, 2000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment