DEV Community

Neha Sharma
Neha Sharma

Posted on • Edited on

Mastering createPortal in ReactJS: How to create portals in ReactJS

Continuing the "Mastering ReactJS Series", in this blog we will learn about createPortal.

To watch my previous videos, please check here:

  1. Error boundary

  2. useLayoutEffect

  3. use state

  4. useEffect

To read blogs:

  1. Link

What is createPortal

As per the official documentation, createPortal let us render some children into a different part of the DOM.

In simple words,createPortal lets you to render the component outside the current parent, or hierarchy.

Image description

Image description
In above diagram, because we are using createPortal, 2nd div will be render outside the parent's div.

Use cases

  1. Tooltips

  2. Modals

  3. Rendering different parts of DOM

  4. React components render to non-react components

  5. React components render to server-side content

Syntax

  1. import { createPortal } from 'react-dom';

  2. createPortal(children, domNode, key?)

children: the jsx

domNode: where you want the portal to be created

key: an optional, A unique string or number to be used as the portal’s key.

Code

  1. render outside current parent hierarchy
import React from "react";
import { createPortal } from "react-dom";

function App() {
  return (
    <div style={{ padding: "100px" }}>
      <h1>React Tooltip with Portal</h1>
      {createPortal(<h1>I am from create portal</h1>, document.getElementById('root') )}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

2 . render inside the root

import React from "react";
import { createPortal } from "react-dom";

function App() {
  return (
    <div style={{ padding: "100px" }}>
      <h1>React Tooltip with Portal</h1>
      {createPortal(<h1>I am from create portal</h1>, document.getElementById('root') )}
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

3 . create a separate component

  return ReactDOM.createPortal(
    <div style={{ ...tooltipStyle, top: position.top, left: position.left }}>
      {text}
    </div>,
    document.body 
  );
Enter fullscreen mode Exit fullscreen mode

Check code examples here

Happy Learning!!

Top comments (2)

Collapse
 
anishamalde profile image
Anisha Malde

This is super useful! Thank-you Neha!

Collapse
 
hellonehha profile image
Neha Sharma

thank you Anisha