I have a situation where I need the components of my application to render in one of two states based on a user click of a button. The problem I am having is that React triggers the full life-cycle of these components, even though all I am changing is the state/props of the components. I am using React 15.6, due to legacy limitations (this app is actually backbone with react embedded), also I cannot use JSX.
props.viewMode === 'ux' || 'dnd' (based on the user button clicks)
Here is the relevant code:
render() {
return this[this.props.viewMode]();
}
ux: function() {
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
**this.props.children**
);
},
dnd: function() {
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
**this.props.children**
)
);
},
When this code is run, it triggers the getInitialState() method in the children, even though the only thing that changes is the viewMode, which is passed down as props from the highest order component down the chain to the child components.
It seems that any reference to props.children outside of the render() method triggers a full life-cycle, destroying the component and creating a new one.
If I refactor the code like this:
render() {
const children = this.props.children.sort((a, b) => { return a.order > b.order });
const elem = this[this.props.viewMode]();
//assign children to elem, e.g. elem.props.children = children;
return elem;
}
ux: function() {
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
**null**
);
},
dnd: function() {
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
**null**
)
);
},
React does not trigger the getInitialState() method in the children.
Does anyone know why this would be? What am I missing?