Components
Portal
Storybook
Portal
The Portal component allows you to render a children into a dedicated DOM node, separate from the main component hierarchy. It provides a way to render components outside their parent component and into a different part of the DOM tree. This can be useful for scenarios, including the creation of modals, tooltips, or any content that necessitates rendering in a distinct location within the DOM.
Imports
1import { Portal } from 'dd360-ds/Portal'
Usage
Here's an example of how you can use the Portal component:
The code snippet below shows how to use the Portal component:
1
2import React, { useEffect, useState } from 'react'
3import { Button, Text } from 'dd360-ds'
4import { Portal } from 'dd360-ds/Portal'
5
6const CustomComponent = () => {
7 const [isactive, setIsactive] = useState(false)
8 const [domLoaded, setDomLoaded] = useState(false)
9
10 useEffect(() => {
11 setDomLoaded(true)
12 }, [])
13
14 return (
15 <div className='relative flex items-center gap-4'>
16 <Text size='base' bold>Portal component</Text>
17 <Button onClick={()=> setIsactive((isactive) => !isactive)}>Toggle Portal</Button>
18 {domLoaded && isactive && (
19 <Portal>
20 <div className='fixed left-1/2 top-1/2 w-40 h-24 flex justify-center items-center border rounded-lg bg-white'>
21 <Text>Hey!!! I am a Portal</Text>
22 </div>
23 </Portal>
24 )}
25 </div>
26 )
27}
28
29export default CustomComponent
30
The IdRoot property is the ID of the root element where the portal will be appended. If not provided, it defaults to 'portal-root'.
Note: When using the Portal component in Next.js may throw an error stating "document is not defined" during server-side rendering (SSR) because the DOM is not accessible on the server. To handle this, the useState hook is modified to conditionally create the container only if the document object is defined. Otherwise, it returns null.
API Reference
Name | Types | Default |
---|---|---|
"children" | ReactNode | - |
"idRoot" | string undefined | portal-root |
Note: This documentation assumes that the audience has basic knowledge of React and how to use components in React applications.