Inserting into a Different DOM Node

Normally, when a component returns an element, it's mounted into the DOM as a child of the nearest parent node. However, sometimes it's useful to insert a child into a different location in the DOM.


RESETRUNFULL
<!DOCTYPE html><html><head></head><body>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div></div>
<div></div>
<script type="text/babel">
function Greeting(props){
  return ReactDOM.createPortal(
    props.children,
    document.querySelectorAll("div")[1]);
}
function Demo(){
  return <Greeting>Hello <b>Ali</b>.</Greeting>;
}
const root = ReactDOM.createRoot(document.querySelectorAll("div")[0]);
root.render(<Demo />);
</script></body></html>

In addition to a fragment, an element or a string can also be inserted.