Trisma
Trisma

Reputation: 763

Conditionally render or prop for modal render

I have a little question about some techniques that are used to render/not render modals.

At the moment there are 2 main ways to do so.

For the first example, we use a visible prop onto the modal and based on that, we will apply a style that will hide the modal. This will be handled by state and then toggled with a button for example :

<Modal
   title="Foo"
   visible={this.state.visible}
 >
   Foo
</Modal>

The second way of doing also use state, but uses a condition to render the modal or not :

{this.state.visible && (
   <Modal title="Foo">
      Foo
   </Modal>
)}

The handy thing with this is that the modal will not be rendered until it should.

So what is the best way of doing? I suppose the 2 are right but is there one that is better than the other?

Upvotes: 2

Views: 2590

Answers (2)

zemil
zemil

Reputation: 5076

Just research the question in UI libs docs: antd, material-ui, semantic-ui.

And you will find the answer => prop (with names open, show, visible etc.) is the best way to control visibility (inner state of component).

For example you can see antd modal that use this package (react-component/dialog): https://github.com/react-component/dialog/blob/master/src/Dialog.tsx

You can return null or use css (display: none; for sample) for invisible modal

Upvotes: 0

onuriltan
onuriltan

Reputation: 3908

Personally second one is better, because by checking the state at Parent Component, you separate Parent Component logic and Child Component logic, since Modal component only responsible for showing the modal, but the logic whether open or close modal belongs to Parent Component logic. But both solutions will work :)

Upvotes: 2

Related Questions