react 16 createPortal

React 16 introduced createPortal function which allows you to render elements outside react Dom, this become useful when you need to dynamically render some elements such as tooltip, modals…

createPortal function can be used inside render method, and returns jsx as usual and where you want to render this element, as example below:

  render() {
    return createPortal(
      

this is a tooltip

, document.getElementById("tooltip") ) }

what if you want to render this whole tooltip dynamically without create a div at start, you can create a component and pass this dynamic div to constructor, and use the component as how you would use component normally.

  // import your react and component...
 
  class Tooltip extends Component {
    constructor(props) {
      super(props);
      this.tooltip = document.createElement("div"); // this is the tooltip element created dynamically.
      document.body.appendChild(this.tooltip); // now append to body...
    }

    render() {
      return createPortal(
        
{this.props.children}
, this.tooltip ) } } class App extends Component { render() { return ( this is content of tooltip ) } }