Our Blog

Portals in react js

Portals in react js

Date : 2018-09-05

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.

 

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() {\r\n  return ReactDOM.createPortal(\r\n    this.props.children,\r\n    domNode,\r\n  );\r\n}

 

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,

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

Let’s render react component,

 

// These two containers are siblings in the DOM\r\nconst appRoot = document.getElementById(\'app-root\');\r\nconst modalRoot = document.getElementById(\'modal-root\');\r\n\r\nclass Modal extends React.Component {\r\n\r\n  render() {\r\n    return ReactDOM.createPortal(\r\n      this.props.children,\r\n      this.el,\r\n    );\r\n  }\r\n}\r\n\r\nclass Parent extends React.Component {\r\n  constructor(props) {\r\n    super(props);\r\n\r\n  }\r\n\r\n  render() {\r\n    return (\r\n      <div onClick={this.handleClick}>\r\n        <Modal>\r\n          <Child />\r\n        </Modal>\r\n      </div>\r\n    );\r\n  }\r\n}\r\n\r\nfunction Child() {\r\n  return (\r\n    <div className=\"modal\">\r\n      <button>Click</button>\r\n    </div>\r\n  );\r\n}\r\n\r\nReactDOM.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!

Read More

Contact Details