React.js / React Advanced Concepts
Creating Modals with Portals in React
This tutorial will explain how to use portals in React to create modals. You will learn how portals provide a way to render children into a DOM node that exists outside the DOM hi…
Section overview
5 resourcesExplores advanced concepts in React, including higher-order components and portals.
Creating Modals with Portals in React
Introduction
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
Step-by-Step Guide
-
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.
Code Examples
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.
Summary
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.
Practice Exercises
- Basic Exercise: Create a simple modal with just text content using React portals.
- Intermediate Exercise: Enhance the modal by adding a close button. When the close button is clicked, the modal should disappear.
- Advanced Exercise: Add an overlay to the modal. When the overlay is clicked, the modal should disappear.
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!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article