Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you hide modals or remove them from the DOM in React?

I'm writing a React application with a lot of modals (but only one ever active at a time with no nested modals), and I'm unsure of which of these two solutions is preferable when it comes to handling showing and hiding these modals:

  1. Have a state boolean variable in the parent component that determines whether or not the modal should be shown. If this boolean variable is false, don't render the component. If it's true, render it. Allow the modal to influence this event via a passed in props callback it can leverage. Example snippets:

    { this.state.prompt === "makePW" ? 
      <MakePassword closeModal={this.closePWModal} /> : 
      null
    }
    

    Now, within the component, it is always visible and does not control its lifecycle. If it is being rendered then it is visible.

  2. Just always show the component in the parent component, like so:

    <MakePassword />
    

    Then within the component itself handle its entire lifecycle. That is, the component will have a boolean state variable for its visibility. Some snippets for this approach:

    <Modal open={this.state.open} onClose={this.closeModal}>
        <Modal.Header>Header</Modal.Header>
        <Modal.Content>Body</Modal.Content>
    </Modal>
    

There are also hybrid approaches, and other solutions as well I'm sure.

Regardless, I suppose the essence of my question is wondering about the preferable solution for showing and hiding modals: is it to always render them and just toggle their visibility, or to actually toggle between adding and removing them from the DOM? And, should the modal itself generally control its lifecycle or should the parent?

like image 362
Chron Bag Avatar asked Dec 06 '25 16:12

Chron Bag


2 Answers

i prefer 1st one but if you want to use the second , i would extend the makepassword component from PureComponent to optimize your component.

Instead of writing shouldComponentUpdate() by hand, you can inherit from React.PureComponent. It is equivalent to implementing shouldComponentUpdate() with a shallow comparison of current and previous props and state. - source react docs

class MakePassword extends React.PureComponent{
    ...
}
like image 190
sravan ganji Avatar answered Dec 08 '25 05:12

sravan ganji


I think it depends on your application.

For example, React-Bootstrap modals stay in the DOM and that allows for nice in/out animations.

like image 38
Danny Delott Avatar answered Dec 08 '25 04:12

Danny Delott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!