React / React Portal / Syntax and API
Home /React /React Portal /Syntax and API

Syntax and API

Syntax and API

React Portals use a single function:


import { createPortal } from 'react-dom';

createPortal(children, container, key?)

Parameters

Parameter Type Required Description
children ReactNode Yes Any valid React content, JSX, strings, arrays, fragments, etc.
container DOM Element Yes Any real DOM element where the children will be mounted.
key string No Optional unique key for the portal (added in React 18). Useful for lists of portals.

Return Value

createPortal() returns a React node (a Portal object). It must be
returned from render() or a functional component’s return statement — or included
in JSX. It is not a regular DOM node.

Import


// Always import from 'react-dom', NOT 'react'
import { createPortal } from 'react-dom';

Minimal Complete Example


import { createPortal } from 'react-dom';

function MyPortal() {
  // Target DOM node — must exist in HTML before React renders
  const target = document.getElementById('portal-root');

  return createPortal(
    <p>I live outside the main React root!</p>,
    target
  );
}

HTML Setup Required


<!-- index.html -->
<body>
  <div id="root"></div>          <!-- React's main root -->
  <div id="portal-root"></div>   <!-- Portal target -->
</body>