Portals in react js

Portals in react js

What is Portal in react js?

Portals in react js provide the way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.



ReactDOM.createPortal(child, container)


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




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


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 overflow: hidden or z-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, HTML file is like this,

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

Let’s render react component,


// These two containers are siblings in the DOMrnconst appRoot = document.getElementById('app-root');rnconst modalRoot = document.getElementById('modal-root');rnrnclass Modal extends React.Component {rnrn  render() {rn    return ReactDOM.createPortal(rn      this.props.children,rn      this.el,rn    );rn  }rn}rnrnclass Parent extends React.Component {rn  constructor(props) {rn    super(props);rnrn  }rnrn  render() {rn    return (rn      <div onClick={this.handleClick}>rn        <Modal>rn          <Child />rn        </Modal>rn      </div>rn    );rn  }rn}rnrnfunction Child() {rn  return (rn    <div className="modal">rn      <button>Click</button>rn    </div>rn  );rn}rnrnReactDOM.render(<Parent />, appRoot);


Explanation of 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!

Send Us A Message

Contact Details