Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React conditional render pattern

Tags:

I have implemented a Modal component that shows a modal dialog on the screen. Normally the modal will show conditionally. There are two ways that I can do this in the render function:

render(){     ...     <Modal show={this.state.showModal}>         // something in modal     </Modal> } 

In the Modal component, I use this.props.show to add a different class to itself. When this is false, it will add a display:none to hide the modal.

Another way is like this:

render(){     ...     { this.state.showModal &&         (<Modal>             // something in modal         </Modal>)     } } 

This uses showModal to decide whether or not to add the Modal in render.

What I want to figure out is:

  1. What's the different between these two ways?
  2. Is one of them better than the other?
  3. Is there another way to do this?

EDIT: It seems that different persons have different preference. For me myself, I prefer what @ErikTheDeveloper said. The ability that show/hide the Modal should keep inside the Modal, and when we don't need to show the Modal, we can return null in the Modal.

I think maybe there's not a certain answer for which way is better. Maybe it's just personal choice?

like image 809
Zhang Chao Avatar asked Dec 18 '15 03:12

Zhang Chao


2 Answers

Your first example always renders the modal, but uses CSS to hide/show it.

Your second example only inserts the modal into the DOM when showing it, else it doesn't show up in the DOM at all.

I prefer not to render it at all unless it's visible (2nd example) but I don't think it matters much either way. The 2nd example also has fewer props now so the Modal component is simpler.

like image 164
Dylan Avatar answered Oct 03 '22 03:10

Dylan


The answer lies in the implementation of Modal component. I'd expect it's render method to be using the show prop to correctly optimize the markup. You should optimize it to eliminate most of the markup when it is not shown.

Why? Implementing the optimization within Modal simplifies its usage, the other components must not be aware/bothered with the costs of rendering it.

EDIT: Because we are using React, the cost of having a dummy Modal component in v-dom is negligible compared to the cost of its dom markup. So even if your other components end up keeping Modal with show=false in their v-dom, it won't matter.

like image 33
hazardous Avatar answered Oct 03 '22 04:10

hazardous