Portal
A first-class way to render child components into a DOM node outside of the parent DOM hierarchy defined by the component tree hierarchy.
install | version | usage |
---|---|---|
yarn add @ciceksepeti/cui-portal | 1.0.0 | import {Portal} from '@ciceksepeti/cui-portal' |
Content​
Portal component mounts its content in a specific area of the DOM. Default renders to end of the body tag. But the render area can be determined by ref or id.
Examples​
Example of a default behavior of Portal component. Renders as 'div' by default.
Default​
import React from 'react';
import { Portal } from '@ciceksepeti/cui-portal';
const Example = () => {
return (
<div>
<div
style={{
padding: '10px',
borderRadius: '6px',
border: '3px solid #52AD36',
}}
>
<span>Container</span>
</div>
<Portal>This box is inside the default portal</Portal>
</div>
);
};
PREVIEW
Portal Default
Container
By Reference​
import React, { useRef } from 'react';
import { Portal } from '@ciceksepeti/cui-portal';
const Example = () => {
const ref = useRef(null);
return (
<div>
<div
ref={ref}
style={{
padding: '10px',
borderRadius: '6px',
border: '3px solid #52AD36',
}}
>
Container
</div>
<Portal containerRef={ref}>
I am in a portal appended next to Container by ref.
</Portal>
</div>
);
};
PREVIEW
Portal by Reference
Example rendering portal into a specified container by reference
Container
By ID​
import React from 'react';
import { Portal } from '@ciceksepeti/cui-portal';
const Example = () => {
return (
<div>
<div
id="my-container"
style={{
padding: '10px',
borderRadius: '6px',
border: '3px solid #52AD36',
}}
>
<span>Container</span>
</div>
<Portal containerId="my-container">
I am in a portal appended next to Container by id.
</Portal>
</div>
);
};
PREVIEW
Portal by ID
Example rendering portal into a specified container by id
Container
Props​
Portal Props​
Name | Type | Default | Required | Description |
as | string | div | - | Changes html tag of portal component which renders to DOM |
containerRef | React.RefObject | - | - | Reference to a container element |
containerId | string | - | - | Element id of a container element |
children | React.Node | - | required | Element which is going to be rendered inside the portal component |
Portal Props​
Name | Type | Description |
useRef | () => {} | useRef hook provides the user to create a connection between related HTMLElement and portal component |