Braden Snell
Braden Snell

Reputation: 105

Unmount React Parent without Unmounting Child

Is it possible for a React component's parent to be unmounted without the child being unmounted? What work arounds exist to achieve this result? Surely there must be some (potentially hacky) way to do this.

Example

When this:

<Parent>
  <Child/>
</Parent>

changes to this:

<Child/>

I would like Parent's lifecycle method componentWillUnmount to be called without Child's lifecycle method componentWillUnmount being called.

I recognize this may not be possible but was wondering if anyone had a creative solution to this problem.

Update

Here's my specific use case (hopefully I do a good enough job explaining this):

I have a higher order component which doesn't introduce any new dom elements but essentially just introduces some new context for the child component. The child component renders slightly differently depending on whether or not this context is present. Unfortunately when I remove and add the parent a new instance of the child is created and it unmounts/remounts. The only issue with this unmounting and remounting is that the child element does some dom measurements to decide whether or not to show a horizontal scroll bar and overflow menu for some of it's elements. When it unmounts/remounts there is an unsightly flash of this menu.

Upvotes: 1

Views: 1473

Answers (1)

Attersson
Attersson

Reputation: 4866

You could handle the rendering logic. For example inside your render function:

  if (showParent) {
    return (
    <Parent>
        <Child/>
    </Parent>);
  } else{
    return <Child/>;
  }

Then whenever the boolean showParent changes the component renders differently.

The super-parent object, calling this render() , should store the state in order to update them and preserve the child (and parent, in case you want to switch it back on).

Therefore it should also contain the state of the child, in order for it to be kept. In other words: move the model hierarchically up to the super parent.

Upvotes: 1

Related Questions