Everything you need as a full stack developer

React Modal with portal implementation

- Posted in React by

TL;DR Modals are a crucial component in modern web development, used for confirming user actions, displaying information, and more. To implement a React modal using the Portal API, we can render children into a different location in the DOM. This approach offers several advantages: it creates a separate DOM node, improves accessibility, and makes styling easier. By combining a basic modal component with a portal component, we can create a fully functional modal that's both accessible and easy to style.

Creating a React Modal with Portal Implementation: A Step-by-Step Guide

As developers, we've all been there - struggling to create a modal window that doesn't disrupt the layout of our application. Modals are an essential component in modern web development, used for confirming user actions, displaying information, and more. In this article, we'll explore how to implement a React modal using the Portal API, which allows us to render children into a different location in the DOM.

What is a Portal?

Before we dive into the implementation, let's quickly cover what a portal is. In React, a portal is an escape hatch that allows you to render children into a different part of the DOM tree. It's essentially a way to move a component from its original position in the DOM to a new location. This can be useful for rendering modals, drawers, or even tooltips.

Why Use Portal?

Using the Portal API to implement a modal offers several advantages:

  • Separate DOM node: By rendering the modal into a separate DOM node, we avoid cluttering our application's layout.
  • Better accessibility: Portals make it easier for screen readers and other assistive technologies to navigate through the DOM.
  • Easier styling: With the modal in its own DOM node, we can apply unique styles without affecting the rest of the application.

Step 1: Setting Up the Modal

Let's start by creating a basic modal component. We'll use React functional components for simplicity:

import React from 'react';

const Modal = ({ isOpen, children }) => {
    if (!isOpen) return null;

    return (
        <div className="modal-overlay">
            <div className="modal-container">
                {children}
            </div>
        </div>
    );
};

export default Modal;

In this example, we've created a Modal component that accepts two props: isOpen and children. The isOpen prop determines whether the modal is visible or not. If it's true, the component returns the modal HTML structure.

Step 2: Creating the Portal

Next, let's create a portal component that will render our modal into a different part of the DOM:

import React from 'react';
import ReactDOM from 'react-dom';

const ModalPortal = ({ children }) => {
    const modalRoot = document.getElementById('modal-root');

    if (!modalRoot) {
        modalRoot = document.createElement('div');
        modalRoot.id = 'modal-root';
        document.body.appendChild(modalRoot);
    }

    return ReactDOM.createPortal(children, modalRoot);
};

export default ModalPortal;

Here, we're using the createPortal function from React DOM to render our children into a different part of the DOM. We've created a portal with an ID of "modal-root" and appended it to the document body.

Step 3: Combining the Portal and Modal

Now that we have both components, let's combine them to create a fully functional modal:

import React from 'react';
import Modal from './Modal';
import ModalPortal from './ModalPortal';

const App = () => {
    const [isOpen, setIsOpen] = useState(false);

    return (
        <div>
            <button onClick={() => setIsOpen(true)}>Open Modal</button>
            {isOpen && (
                <ModalPortal>
                    <Modal isOpen={true}>
                        <h1>This is a modal!</h1>
                    </Modal>
                </ModalPortal>
            )}
        </div>
    );
};

In this example, we've created an App component that toggles the modal visibility when clicked. We're using the useState hook to manage the isOpen state.

Conclusion

By following these steps, you can create a React modal with portal implementation that's both accessible and easy to style. Portals offer a powerful way to render components into different parts of the DOM, making them ideal for modals, drawers, and other interactive elements. Experiment with this example code to see how you can adapt it to your own projects!

Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more