Learn React, React, React Tutorial

Portals in React Explained

In React, a portal is a way to render a child component at a different location in the HTML document tree than...

Written by Shivangi Rajde · 3 min read >
Portals in React Explained

In React, a portal is a way to render a child component at a different location in the HTML document tree than its parent component. Portals allow you to render a component’s children into a different DOM subtree than the one in which the parent component is mounted. This can be useful when you need to render a component outside of the normal document flow, for example, in a modal or tooltip.

To use a portal in React, you first need to create a new DOM node that will act as the portal container. You can create this node using the “document.createElement” method, or by selecting an existing DOM node using the “document.querySelector” method.

Once you have your portal container, you can render your child component into it using the “ReactDOM.createPortal” method. This method takes two arguments: the first is the component you want to render, and the second is the DOM node that will act as the portal container.

Here’s an example of how you might use a portal to render a modal dialog box in React:

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

class Modal extends React.Component {
  render() {
    return ReactDOM.createPortal(
      <div className="modal">
        <div className="modal-content">
          {this.props.children}
        </div>
      </div>,
      document.getElementById('modal-root')
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>My App</h1>
        <Modal>
          <p>This is some modal content!</p>
        </Modal>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

In this example, we define a “Modalcomponent that renders its children into a portal container with the ID “modal-root”. We then use this “Modalcomponent in our App component to render a modal dialog box with some content. The content is rendered outside of the normal document flow and is positioned using CSS.

Portals are a powerful feature of React that allows you to render components in a flexible and dynamic way. However, they should be used sparingly and only when necessary, as they can make your code more complex and harder to maintain.

How to implement Portals in React?

Step 1: Create a container for the portal

This container should be outside of the root node where your React app is mounted. You can create this container using document.createElement and append it to the document body.

For example:

const portalContainer = document.createElement('div');
portalContainer.setAttribute('id', 'portal-container');
document.body.appendChild(portalContainer);

Step 2: Create a component that will be rendered inside the portal container.

This component can be any regular React component that you want to render inside the portal.

For example:

function MyComponent() {
  return <div>My Component</div>;
}

Step 3: Render the component using the createPortal function from the react-dom package.

This function takes two arguments: the first is the component that you want to render, and the second is the container where you want to render the component.

For example:

import ReactDOM from 'react-dom';

ReactDOM.createPortal(<MyComponent />, document.getElementById('portal-container'));

Step 4: Render your React app as usual.

ReactDOM.render(<App />, document.getElementById('root'));

With these steps, you can use a portal to render a React component outside of its parent component’s DOM hierarchy. This can be useful for things like modals, dropdown menus, and tooltips.

Remember that portals should be used sparingly and only when necessary, as they can make your code harder to understand and maintain.

What is event bubbling?

Event bubbling is a mechanism in JavaScript where events that occur on a child element are also triggered on its parent elements, all the way up to the document root. This means that if an event occurs on a deeply nested element, that event will also be triggered on all of its ancestor elements.

Implement Event Bubbling using Portals in React

When using portals in React, event bubbling can work in a similar way. If you have a portal that renders a component outside of its parent component’s DOM hierarchy, events that occur within that component can bubble up to the parent component and beyond.

For example, imagine you have a component that renders a button inside a portal:

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

function PortalButton() {
  const portalContainer = document.getElementById('portal-container');

  return ReactDOM.createPortal(
    <button onClick={() => console.log('Portal button clicked')}>
      Click me!
    </button>,
    portalContainer
  );
}

If this component is rendered within a parent component, and the parent component has an event listener for the “clickevent, that event listener will also be triggered when the button is clicked:

function ParentComponent() {
  const handleClick = () => console.log('Parent component clicked');

  return (
    <div onClick={handleClick}>
      <h1>Parent Component</h1>
      <PortalButton />
    </div>
  );
}

In this example, if you click the portal button, both the “PortalButtoncomponent’s onClick handler and the “ParentComponentcomponent’s “onClickhandler will be triggered, due to event bubbling.

It’s important to keep event bubbling in mind when using portals in React, as events that occur within a portal can have unexpected effects on the parent component and other components higher up in the DOM hierarchy. To avoid these issues, you can use techniques like event delegation or stopping the propagation of events to prevent events from bubbling up to higher-level components.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *