October 5, 2021 12:16 am GMT
Original Link: https://dev.to/byusa/the-use-of-portals-in-react-39pj
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'
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;
Original Link: https://dev.to/byusa/the-use-of-portals-in-react-39pj
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To