I would like to know if there is a way to only render a parent component when its child is rendered and vis versa. If you google the title you find quite a few entries but nothing the would work for my case because my elements aren't undefined
or null
, for example. Imagine a Parent:
class Parent extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<div className="container">
{this.props.children}
</div>
</div>
);
}
}
The following child might be depended on some settings. For instance, only show if a boolean is true.
class Child extends React.Component {
constructor(props){
super(props);
const showChild = Settings.get(...);
this.state = {
visible:showChild
}
}
render() {
const showHello = this.state.visible ? <div>Hello</div> : "";
return (
<div>{showHello}</div>
);
}
}
In my layout I scaffold it like this:
class Layout extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<Parent>
<Child />
</Parent>
);
}
}
Is it possible to unmount Parent
if that Child
element is not rendered? Thank you.
Update: A use case is if I want this Parent
and Child
to be in a Layout
and Parent
has a container class with a larger padding or margin because it is still in the component tree. If Child isn't rendered a large gap remains within the Layout and it just looks odd.
React was not designed with this workflow in mind, in fact the opposite: data is explicitly passed down the DOM tree, while actions are passed upward. By extension, React must render your Parent
before your Child
.
I'd suggest refactoring your Parent
and Child
to the point where Parent
is aware of which settings its Child
needs; insofar as your Child
component is engaged with:
<Child settings={settings} />
To reiterate, this is also a more natural approach to React, whereby data is explicitly passed downward, and not implicitly loaded in the Child
(although there's always exceptions, like the ability of connect()
components with react-redux
). But a benefit to this approach is that now Parent
is able to determine whether or not to render its Child
.
But what about the rendering of Parent
? Don't we want to inhibit that too? If you do, then you'll need your Layout
component to be aware of what it's Parent
component needs, therefore:
<Parent settings={settings} />
This is a common approach to React
since rendering down the DOM hierarchy is a must.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With