The goal of this tutorial is to teach you how to use portals in React to create modals. We will learn how portals provide a seamless way to render child components into a DOM node outside the parent component's DOM hierarchy.
By the end of this tutorial, you will be able to:
- Understand what React portals are and how they work
- Create a modal using React portals
Prerequisites:
- Basic understanding of React
- Familiarity with JSX, HTML, CSS
- Basic knowledge of JavaScript
Understanding React Portals: React Portals provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. This feature is useful when a child component needs to break out of its container for layout reasons like an overlay, hovercards, or modals!
Creating a Modal with React Portals: We will create a simple modal in React using portals. The modal will be rendered outside the root DOM node of our React application.
Let's walk through the code for creating a simple modal:
Create a new file for the Modal component: We will create a new file, Modal.js
, and import React and ReactDOM.
javascript
import React from 'react';
import ReactDOM from 'react-dom';
Creating a Modal Component: In the same file, we will create a functional component named Modal
.
```javascript
const Modal = ({ children }) => {
// Create a new div that wraps the component
const el = document.createElement('div');
// Ensure that the modal is appended to body
useEffect(() => {
// Append to body
document.body.appendChild(el);
// Cleanup function
return () => {
document.body.removeChild(el);
}
}, []);
// Use a portal to render the children into the element
return ReactDOM.createPortal(
children,
el,
);
}
export default Modal;
```
In this example, we created a new div
that wraps the component and ensured that the modal is appended to the body. We then used ReactDOM.createPortal
to render the children into the element.
We covered the concept of React portals and how to use them to render children components outside the parent component's DOM hierarchy. We also walked through a practical example of creating a modal using React portals.
Next steps would be to explore more complex use-cases of React portals and enhancing the modal with more features like animations, event handling, etc.
You can read more about React Portals in the official React documentation.
For each exercise, ensure you understand how the modal is being rendered outside the root DOM node using portals. As a tip, you can inspect the page and see how the modal's DOM node is directly under the body, not under the root node.
Happy coding!