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…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores 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

  1. 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!

  2. 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:

  1. 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';

  2. 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

  1. Basic Exercise: Create a simple modal with just text content using React portals.
  2. Intermediate Exercise: Enhance the modal by adding a close button. When the close button is clicked, the modal should disappear.
  3. 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help