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
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.