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>

Step 2
Then import MyReactDOM from ‘react-dom’
Fe…


This content originally appeared on DEV Community and was authored by Serge Jabo Byusa

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>

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'

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>
  )
} 

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;


This content originally appeared on DEV Community and was authored by Serge Jabo Byusa


Print Share Comment Cite Upload Translate Updates
APA

Serge Jabo Byusa | Sciencx (2021-10-05T00:16:38+00:00) The Use of Portals in React. Retrieved from https://www.scien.cx/2021/10/05/the-use-of-portals-in-react/

MLA
" » The Use of Portals in React." Serge Jabo Byusa | Sciencx - Tuesday October 5, 2021, https://www.scien.cx/2021/10/05/the-use-of-portals-in-react/
HARVARD
Serge Jabo Byusa | Sciencx Tuesday October 5, 2021 » The Use of Portals in React., viewed ,<https://www.scien.cx/2021/10/05/the-use-of-portals-in-react/>
VANCOUVER
Serge Jabo Byusa | Sciencx - » The Use of Portals in React. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/05/the-use-of-portals-in-react/
CHICAGO
" » The Use of Portals in React." Serge Jabo Byusa | Sciencx - Accessed . https://www.scien.cx/2021/10/05/the-use-of-portals-in-react/
IEEE
" » The Use of Portals in React." Serge Jabo Byusa | Sciencx [Online]. Available: https://www.scien.cx/2021/10/05/the-use-of-portals-in-react/. [Accessed: ]
rf:citation
» The Use of Portals in React | Serge Jabo Byusa | Sciencx | https://www.scien.cx/2021/10/05/the-use-of-portals-in-react/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.