React Portal

What is React Portal?

React Portal provide the way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

 

Format

ReactDOM.createPortal(child, container)

 

where the child is the Component which will be rendered at the place of the container which is dom node.

 

Implementation:

 

render() {
  return ReactDOM.createPortal(
    this.props.children,
    domNode,
  );
}

 

where domNode is the parent DOM element for the children Component will be rendered.

 

Practical Usage Scenario: A typical use case for portals is when a parent component has an oroverflow: hiddenz-index style, but you need the child to visually “break out” of its container. For example, dialogs, hovercards, and tooltips.

 

Event Bubbling through Portals:

Even though a portal can be anywhere in the DOM tree, it behaves like a normal React child. Features like context work exactly the same regardless of whether the child is a portal, as the portal still exists in the React tree regardless of position in the DOM tree.

This includes event bubbling. An event fired from inside a portal will propagate to ancestors in the containing React tree, even if those elements are not ancestors in the DOM tree. Assuming the following HTML structure:

 

Suppose, the HTML file is like this,


<html>
  <body>
    <div id="app-root"></div>
    <div id="modal-root"></div>
  </body>
</html>


Let’s render react component,

 

// These two containers are siblings in the DOM
const appRoot = document.getElementById('app-root');
const modalRoot = document.getElementById('modal-root');

class Modal extends React.Component {

  render() {
    return ReactDOM.createPortal(
      this.props.children,
      this.el,
    );
  }
}

class Parent extends React.Component {
  constructor(props) {
    super(props);

  }

  render() {
    return (
      <div onClick={this.handleClick}>
        <Modal>
          <Child />
        </Modal>
      </div>
    );
  }
}

function Child() {
  return (
    <div className="modal">
      <button>Click</button>
    </div>
  );
}

ReactDOM.render(<Parent />, appRoot);

 

Explanation of react portal code: 

  1. We have rendered the Parent Component at appRoot DOM.
  2. We have included Modal component inside parent Component.
  3. Although, Modal is inside Parent Component which is inside appRoot DOM.
  4. BUT, Portal will render component outside appRoot Component.

Looking for ReactJS Development Company, hire our dedicated developers!

Also, Read:

How Diff Algorithm is implemented in Reactjs?

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.