Create Modal in React JS in 2023 with ReactDOM.createPortal

 

ReactDOM.createPortal is a method provided by the ReactDOM library in React.js that allows you to render a React component into a different DOM node than the one that is associated with the parent component. This can be useful for creating modals, dialogs, or other types of UI elements that should be rendered outside of the main application structure.


When you use createPortal, React will create a new "portal" and attach it to the DOM node that you specify. This allows you to add content to the DOM that is outside of the React component tree, and it will still be managed by React. This is useful for situations where you want to render a component that should be positioned outside of the main application structure, but still wants to be managed by React.


In order to use createPortal, you need to import ReactDOM library and call the createPortal function, passing two arguments:


1: The React element you want to render
2: The DOM node where you want to render it.



Here is the Example

import ReactDOM from 'react-dom'; const modalRoot = document.getElementById('modal-root'); const Modal = ({ children }) => { return ReactDOM.createPortal(children, modalRoot); };


Here is the complete source code 

Subscribe - Thapa Technical