Home > Software design >  do we really need react portal
do we really need react portal

Time:04-01

I understand that we might want to use react portal when we are trying to add component out side rendered hierarchy tree in react as example if we want to pop up Model component above anything else in the page

but what I can not fully understand why don't we just put this Model component in the same hierarchy tree but in the top of it and make it rendering depends on a variable we get from react context or redux

function App(){
  const showModel ; //variable we get from redux or react context
   return (<>
    {showModel? </Model>:""}
    <div id="main"></>
    </>)

}

CodePudding user response:

You're right. Strictly speaking, you might never have to use portals if you can manage the styling necessary to get the other component to render at the proper place. But portals can make it a lot easier - with them, the existing styling for the other container and everything that surrounds it will just continue to work when your component is inserted inside, with minimal to no adjustment on your part. Putting the modal right next to your other React code (in terms of the DOM hierarchy), like

<Model />
<div id="main" />

may work, but it could well require somewhat convoluted logic if the visual position desired for the Modal is the same as an already existing element in the DOM. Portals will sometimes make it a lot easier. (And sometimes they won't help at all, such as when the <Model /> has no need to be positioned relative to an existing element)

  • Related