Parent class has several children components, all the children are instantiated inside render method, so any change to parent state will cause all the children to be re instantiated , everytime render is called react creates new instance of children, there by loosing state of children, in order to reuse the child instance I tried retrieving child instance using parent.refs.childRef , but this gives me error
Uncaught Error: Objects are not valid as a React child
, here is my code
placeHolderComponent(){
let component;
let palceHolderValue=this.state.uiState.placeHolder;
let classInstance=this;
if(palceHolderValue=='empty'){
component=<EmptyComponent></EmptyComponent>
}
else if(palceHolderValue=='search'){
component= classInstance.refs.gpSearchComponent!=null? classInstance.refs.gpSearchComponent: <GpSearch ref="gpSearchComponent"/>
}
return component;
}
here GpSearch Component is instantiated with a ref attribute , and code checks if parent.refs.childComponentRefId is not null then render that instance, instead a new instance. I am getting this error
Uncaught Error: Objects are not valid as a React child (.... If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons
1 Answer 1
"any change to parent state will cause all the children to be re instantiated"
No, any change to parent state can cause a re-render of parent and its children. Child components are not recreated, but re-rendered (albeit you can avoid re-rendering of children with the life cycle hook shouldComponentUpdate
).
"loosing state of children"
again No. Children won't lose their internal state when the're re-rendered.
The error is presumably thrown by this line:
component = classInstance.refs.gpSearchComponent != null ? classInstance.refs.gpSearchComponent: <GpSearch ref="gpSearchComponent"/>
because classInstance.refs.gpSearchComponent
is an object and as React complains "Uncaught Error: Objects are not valid as a React child".
if(palceHolderValue=='empty'){
component=<EmptyComponent></EmptyComponent>
}
else if(palceHolderValue=='search'){
component= classInstance.refs.gpSearchComponent!=null? classInstance.refs.gpSearchComponent: <GpSearch ref="gpSearchComponent"/>
}
return component;
according to ^^ this code, I think you either render an EmptyComponent
or GpSearch
component. So whenever the placeHolderValue
changes you unmount the currently re-rendered component. That is how your component are re-instantiated each time, and thus you lose internal state of child components.
An alternative approach is, you keep the state of children in your parent (as parent component's state) and pass it as props to children as required.