Skip to content

Instantly share code, notes, and snippets.

@hex13
Forked from anonymous/main.js
Last active January 9, 2016 12:49
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 hex13/339d89cc0abe6147f997 to your computer and use it in GitHub Desktop.
Save hex13/339d89cc0abe6147f997 to your computer and use it in GitHub Desktop.
React triggers remounting when we use function as react component ( <Renderer /> ). When we don't and run Renderer() it's okay
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},
]
},
]
};
// function that returns stateless React component (i.e. just function)
// something like factory design pattern
function createRenderer(node, children) {
return () => (<li>{node.name}<ul>{children}</ul></li>);
}
// 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);
// ****** HERE: ******
//return Renderer(); // uncommment and it's okay.
return <Renderer /> // when this executes there is unmounting-mounting
}
}
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