laurent
laurent

Reputation: 90863

How to hide a component without unmounting it?

I've got a list component that I would like to keep in the DOM whenever it's not needed so that the scroll position is not lost.

I've tried setting the style to {display: 'none'} but this unmounts the component. I've also tried setting { flex: 0.0001 } which kind of works but it feels like a hack (which they might optimise to "0" later on) and it creates layout glitches when the component is shown/hidden.

Any idea what would be the proper way to do this?

Upvotes: 14

Views: 15311

Answers (3)

Xarvalus
Xarvalus

Reputation: 3021

I have found that in recent React Native the approach with:

{ display: 'none' }

Do the works fine for me, my Tab component switches layouts without unmounting it's contents.

Tested on: RN 0.58.1, iPhone X 12.1.

Upvotes: 17

albert200000
albert200000

Reputation: 363

Try this:

<div style={{visibility: this.state.hidden ? 'hidden' : 'visible'}}>
    content
</div>

Upvotes: 0

Matt Aft
Matt Aft

Reputation: 8936

If I understand correctly, you want the component to stay mounted but not take up any space or render anything? What if you just pass a hide property to the component which will just return an empty view in the render if it's true.

Upvotes: 0

Related Questions