24

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?

3
  • one hides, one remove, but the net effect is the same. if you have insertion costs, like with a web component, then hiding might be a hair more CPU efficient, but it doesn't much matter.
    – dandavis
    Dec 18, 2015 at 3:43
  • I've answered below (with code examples) with the approach that has worked well for my team and I. I'm curious how you (and other answerers) are handling "closing" the modal? Considering most modals have UX such as closing on events such as: pressing [ESC], clicking "x", clicking outside the modal, etc... That is my reasoning for passing down the close prop/callback in my examples below.
    – Erik Aybar
    Dec 18, 2015 at 15:03
  • What Im using is also passing a closeHandler to the props of Modal. In the closeHandler set state showModal to false. And I also pass a submitHandler to the Modal, which will do something more than close the Modal.
    – Zhang Chao
    Dec 19, 2015 at 2:55

6 Answers 6

7

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.

5

I prefer the second approach too. Even though React minimizes the negative impact of having additional elements in DOM, it is always a good practice to not render elements that are not meant to be. I would expand on that thinking and extract the logic of showing/hiding the Modal in separate function and call it in render.

render: function(){
   ...
   {this.renderModal()}
},
renderModal: function(){
    ...
    {this.state.showModal && (<Modal />)}
}

This gives you flexibility to add additional conditions at a single location and keeps your render function small and easily understandable.

4

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.

2

I answered a similar question a while back relating to the best way of opening/closing modal

I have spent a lot of time with React since then and learned a few lessons along the way.

I've found this general approach to work nicely for dealing with modals: Using a fully controlled "dumb" component that takes 3 props.

  • show: Boolean - Is the modal visible?
  • close: Function - The modal needs a callback in order to close itself
  • children: node - The contents of the modal

See React Docs for info on Controlled Components


To answer your question about the difference between the two, is that IMO option 1 provides a cleaner and more flexible API to work with while option 2 is more minimalist.

With option 1 you could take care of hiding/showing by using either CSS or returning null from <Modal>. I would recommend returning null since the modal contents will simply not be rendered vs. rendering them and "hiding" them via CSS.

Option 2 forces the more verbose "JSX way" of conditionally rendering which I think is appropriate in many cases. However I feel like the concept of a modal merits the hiding/showing being a part of a <Modal> components API (props/methods/etc...)


Why pass down the close prop/callback?

Considering most modals have UX such as closing on events such as: pressing [ESC], clicking "x", clicking outside the modal, etc... a modal needs to be informed of how to "close itself" via passing down the close prop/callback in my examples below.


Code Examples

// The simple, fully controlled Modal component
const Modal = React.createClass({
  render() {
    const {
      show,     // Boolean - Is the modal visible?
      close,    // Function - The modal needs a function to "close itself"
      children, // node - The contents of the modal 
    } = this.props;
    return !show ? null : (
      <div className="some-class-for-styling">
        <a onClick={close}>x</a>
        {children}
      </div>
    );
  }
});

const UsesModal = React.createClass({
  setEditing(editing) {
    this.setState({editing});
  },

  render() {
    // `editing` could come from anywhere. 
    // Could be derived from props, 
    // or managed locally as state, anywhere really....
    const {editing} = this.state;
    return (
      <div>
        <h1>Some Great Component</h1>
        <a onClick={() => this.setEditing(true)}>Show Modal!</a>
        <Modal show={editing} close={() => this.setEditing(false)}>
          Some great modal content... show based on UsesModal.state.editing
        </Modal>
      </div>
    );
  }
});

And if you want to let the modal manage its own state, you can wrap up the "dumb" modal with a slightly smarter component and make use of refs and "public component methods" (although I've found that sticking with the simplified approach usually results in less headache and regret ;))

const SmarterModal = React.createClass({
  close() {
    this.setState({show: false});
  },

  open() {
    this.setState({show: true});
  },

  render() {
    const {children} = this.props;
    const {show} = this.state;
    return (
      <Modal show={show} close={this.close}>
        {children}
      </Modal>
    );
  }
});

const UsesSmarterModal = React.createClass({
  render() {
    return (
      <div>
        <h1>Some Great Component</h1>
        <a onClick={() => this.refs.my_smarter_modal.open()}>Show Modal!</a>
        <SmarterModal ref="my_smarter_modal">
          Some great modal content... show based on SmarterModals own internal state
        </SmarterModal>
      </div>
    );
  }
});

There are a number of ways you can wrap up the simple <Modal>, but I feel like it serves as a solid foundation and the data flow plays nicely to allow computing/deriving "is the modal open" from wherever makes the most sense. This is the approach I've found to work nicely.

1

This is just one more way to do this, react if module:

var Node = require('react-if-comp');
...
var Test = React.createClass({
    render: function() {
        return <Node if={this.state.showModal}
                     then={<Modal>// something in modal</Modal>} />;
    }
});
1
  • Which way inside the 'react-if-comp' use to render components conditionally?
    – Zhang Chao
    Jan 10, 2016 at 8:35
0

Take a look at https://github.com/fckt/react-layer-stack, it allows to show/hide something which is rendering in different part of tree, but logically connected with a top-level component (which allows to use variables from it at the same time):

import { Layer, LayerContext } from 'react-layer-stack'
// ... for each `object` in array of `objects`
  const modalId = 'DeleteObjectConfirmation' + objects[rowIndex].id
  return (
    <Cell {...props}>
        // the layer definition. The content will show up in the LayerStackMountPoint when `show(modalId)` be fired in LayerContext
        <Layer use={[objects[rowIndex], rowIndex]} id={modalId}> {({
            hideMe, // alias for `hide(modalId)`
            index } // useful to know to set zIndex, for example
            , e) => // access to the arguments (click event data in this example)
          <Modal onClick={ hideMe } zIndex={(index + 1) * 1000}>
            <ConfirmationDialog
              title={ 'Delete' }
              message={ "You're about to delete to " + '"' + objects[rowIndex].name + '"' }
              confirmButton={ <Button type="primary">DELETE</Button> }
              onConfirm={ this.handleDeleteObject.bind(this, objects[rowIndex].name, hideMe) } // hide after confirmation
              close={ hideMe } />
          </Modal> }
        </Layer>

        // this is the toggle for Layer with `id === modalId` can be defined everywhere in the components tree
        <LayerContext id={ modalId }> {({showMe}) => // showMe is alias for `show(modalId)`
          <div style={styles.iconOverlay} onClick={ (e) => showMe(e) }> // additional arguments can be passed (like event)
            <Icon type="trash" />
          </div> }
        </LayerContext>
    </Cell>)
// ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.