Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Render a parent only when Child is rendered

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.

like image 443
MichelH Avatar asked Oct 31 '22 04:10

MichelH


1 Answers

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.

like image 87
lux Avatar answered Nov 15 '22 05:11

lux