DEV Community

Cover image for The Use of Portals in React
Serge Jabo Byusa
Serge Jabo Byusa

Posted on • Updated on

The Use of Portals in React

Getting a cleaner DOM with Portals

Step 1
Got inside public/index.html and add
the roots near the

<div id="backdrop-root"></div>
<div id="overlay-root"></div>
Enter fullscreen mode Exit fullscreen mode

Step 2
Then import MyReactDOM from 'react-dom'
Fell free to name anything you want. I named it MyReactDOM in this example

import MyReactDOM from 'react-dom'
Enter fullscreen mode Exit fullscreen mode

Step 3
Create methods that returns jsx to be used

const Backdrop = (props) => {
  return (<div onClick={props.onConfirm} />)
}

const ModelOverLay = (props) =>{
  return ( 
    <Card>
      <header>
        <h2> Invalid Input</h2>
      </header>
      <div>
        <p> The input is invalid </p>
      </div>
      <footer>
        <Button onClick={props.onConfirm}>Okay</Button>
      </footer>
    </Card>
  )
} 

Enter fullscreen mode Exit fullscreen mode

Step 4
Put the two methods your exported component
syntax:
ReactDOM.createPortal(child, container)

const ErrorModal = (props) => {
  return (
 <React.Fragment>

 {MyReactDOM.createPortal( 
   <Backdrop onConfirm={props.onConfirm}/>, 
    document.getElementById('backdrop-root'))}

 {MyReactDOM.createPortal(
  <ModelOverLay onConfirm={props.onConfirm}/>, 
   document.getElementById('overlay-root'))}

 </React.Fragment>
  );

};

export default ErrorModal;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)