Portal
It uses createPortal (opens in a new tab) to render some children into a different part of the DOM.
Usage
Default behaviour is to render the children at the end of document.body
.
I'm rendered where the component is used.
Scroll to the bottom of the page to see the yellow portal in this example.
import { Fragment } from 'react';
import { usePortal, UsePortalProps } from '@norr/components';
const Portal = (props: UsePortalProps) => {
const { portalProps } = usePortal(props);
return <Fragment {...portalProps} />;
};
const Component = () => {
return (
<>
<div style={{ backgroundColor: 'purple' }}>
I'm rendered where the component is used.
</div>
<Portal>
<div style={{ backgroundColor: 'yellow' }}>
I'm portaled at the end of document.body.
</div>
</Portal>
</>
);
};
Custom container
You can tell the component in which container it should be rendered.
I'm rendered where the component is used.
import { Fragment, useRef } from 'react';
import { usePortal, UsePortalProps } from '@norr/components';
const Portal = (props: UsePortalProps) => {
const { portalProps } = usePortal(props);
return <Fragment {...portalProps} />;
};
const Component = () => {
const containerRef = useRef(null);
return (
<>
<div ref={containerRef} style={{ backgroundColor: 'purple' }}>
I'm rendered where the component is used.
</div>
<Portal container={containerRef}>
<div style={{ backgroundColor: 'yellow' }}>
I'm portaled at the end of the purple box. 👆
</div>
</Portal>
</>
);
};