

{"id":113483,"date":"2023-06-16T09:00:53","date_gmt":"2023-06-16T03:30:53","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=113483"},"modified":"2023-06-16T10:00:24","modified_gmt":"2023-06-16T04:30:24","slug":"react-portal","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/react-portal\/","title":{"rendered":"React Portal"},"content":{"rendered":"<p>React Portal is an advanced feature in React that enables a component to render its children into a different DOM.<br \/>\nThis can be useful when rendering a modal tooltip outside the current component tree without affecting the CSS styles.<\/p>\n<h3>What are React Portals?<\/h3>\n<p>React Portals are a way to render a child component into a different part of the DOM tree that is outside of the parent component hierarchy. Normally, when you render a component, it is added to the DOM as a child of the parent component. However, with portals, you can specify a different DOM node for the component to render into.<\/p>\n<p>This can be especially useful when you need to render a modal or tooltip outside of the current component tree. For example, if you have a long list of items and you want to show a tooltip when the user hovers over one of the items, you could render the tooltip.<\/p>\n<h3>When to use React Portals?<\/h3>\n<p><strong>Modals:<\/strong> You can render modals outside the current component tree to avoid z-index conflicts with other elements on the page.<\/p>\n<p><strong>Tooltips:<\/strong> You can render tooltips outside the current component tree to avoid layout issues.<br \/>\nCustom Dropdowns: You can render dropdown menus outside the current component tree to avoid issues with overflow and positioning.<\/p>\n<p><strong>Parent CSS Conflicts:<\/strong> You can render a component outside the parent component hierarchy to avoid conflicts with the parent component&#8217;s CSS styles.<\/p>\n<h3>How to Implement React Portals?<\/h3>\n<p>To create a React Portal, you need to first create a new DOM node that will act as the container for the portal. This can be done using the createPortal() function provided by React. The createPortal() function takes two arguments: a child component to render and a DOM node to render the component into.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import React, { useState } from 'react';\r\nimport ReactDOM from 'react-dom';\r\n\r\nconst Modal = ({ onClose, children }) =&gt; {\r\n  const [modalContainer] = useState(() =&gt; {\r\n    const el = document.createElement('div');\r\n    el.className = 'modal';\r\n    return el;\r\n  });\r\n\r\n  React.useEffect(() =&gt; {\r\n    const modalRoot = document.getElementById('modal-root');\r\n    modalRoot.appendChild(modalContainer);\r\n    return () =&gt; {\r\n      modalRoot.removeChild(modalContainer);\r\n    };\r\n  }, [modalContainer]);\r\n\r\n  return ReactDOM.createPortal(\r\n    &lt;div className=\"modal-overlay\"&gt;\r\n      &lt;div className=\"modal-content\"&gt;\r\n        &lt;button onClick={onClose}&gt;Close&lt;\/button&gt;\r\n        {children}\r\n      &lt;\/div&gt;\r\n    &lt;\/div&gt;,\r\n    modalContainer\r\n  );\r\n};\r\n\r\nconst App = () =&gt; {\r\n  const [showModal, setShowModal] = useState(false);\r\n\r\n  const handleCloseModal = () =&gt; {\r\n    setShowModal(false);\r\n  };\r\n\r\n  return (\r\n    &lt;div&gt;\r\n      &lt;h1&gt;React Portals Demo&lt;\/h1&gt;\r\n      &lt;button onClick={() =&gt; setShowModal(true)}&gt;Show Modal&lt;\/button&gt;\r\n      {showModal &amp;&amp; (\r\n        &lt;Modal onClose={handleCloseModal}&gt;\r\n          &lt;p&gt;This is a modal dialog.&lt;\/p&gt;\r\n        &lt;\/Modal&gt;\r\n      )}\r\n    &lt;\/div&gt;\r\n  );\r\n};\r\n\r\nReactDOM.render(&lt;App \/&gt;, document.getElementById('app'));\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-portal-implementation.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-113643\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-portal-implementation.png\" alt=\"react portal implementation\" width=\"424\" height=\"148\" \/><\/a><\/p>\n<h3>Benefits of Portals in React<\/h3>\n<h4>1. Improved Structure and Readability<\/h4>\n<p>One of the main benefits of using portals is the improved structure and readability of your code. When you use a portal to render a component in a specific location in the DOM, your code is more readable.<\/p>\n<h4>2. Separation of Concerns<\/h4>\n<p>Portals also enable you to separate the concerns of your components. For example, you may have a component that is responsible for rendering a specific UI element, such as a tooltip or drop-down menu. By using a portal to render this UI element, you can separate the rendering logic from the main component logic.<\/p>\n<p>This separation of concerns makes your components more modular and easier to maintain. If you need to change the rendering logic for the UI element, you can simply update the portal.<\/p>\n<h4>3. Flexibility<\/h4>\n<p>Portals also give you more flexibility in how you structure your components. With portals, you can render a component at a specific location in the DOM, regardless of its position in the component hierarchy.<\/p>\n<h3>Event Bubbling through portals in React<\/h3>\n<p>Portals in React are a way to render a child component outside of its parent DOM hierarchy. This is useful when you need to render a component in a different part of the DOM tree, such as a modal or a dropdown menu. Portals are created using the ReactDOM.createPortal() method, which takes two arguments: the child component to render, and a DOM node where to render it.<\/p>\n<p>When you use portals, event bubbling can behave differently from regular React components. By default, events that originate from a portal child will not bubble up to the parent component, since the portal child is rendered outside of its parent&#8217;s DOM hierarchy. This can be problematic when you need to handle events that occur inside a portal component.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class PortalChild extends React.Component {\r\n  handleClick = (event) =&gt; {\r\n    this.props.forwardedRef.current.dispatchEvent(\r\n      new MouseEvent('click', {\r\n        view: window,\r\n        bubbles: true,\r\n        cancelable: true,\r\n      })\r\n    );\r\n  };\r\n\r\n  render() {\r\n    return (\r\n      &lt;div onClick={this.handleClick}&gt;Portal Child&lt;\/div&gt;\r\n    );\r\n  }\r\n}\r\n\r\nconst PortalParent = () =&gt; {\r\n  const portalNode = document.getElementById('portal');\r\n  const ref = React.useRef(null);\r\n\r\n  return ReactDOM.createPortal(\r\n    &lt;PortalChild forwardedRef={ref} \/&gt;,\r\n    portalNode,\r\n  );\r\n};\r\n\r\nconst App = () =&gt; (\r\n  &lt;&gt;\r\n    &lt;div id=\"parent\"&gt;\r\n      Parent Component\r\n    &lt;\/div&gt;\r\n    &lt;div id=\"portal\" \/&gt;\r\n    &lt;PortalParent \/&gt;\r\n  &lt;\/&gt;\r\n);\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/event-bubbling.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-113644\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/event-bubbling.png\" alt=\"event bubbling\" width=\"491\" height=\"178\" \/><\/a><\/p>\n<h3>Conclusion<\/h3>\n<p>React portals are a powerful tool that enables you to render a component in a specific location in the DOM. Portals offer several benefits, including improved structure and readability, the separation of concerns, and flexibility in how you structure your components.<\/p>\n<p>By using portals in your React applications, you can create more modular, maintainable, and flexible components that are easier to read and understand.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>React Portal is an advanced feature in React that enables a component to render its children into a different DOM. This can be useful when rendering a modal tooltip outside the current component tree&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":113642,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27227],"tags":[27429,27430],"class_list":["post-113483","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-react-tutorials","tag-react-portal","tag-react-portals"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>React Portal - DataFlair<\/title>\n<meta name=\"description\" content=\"React portal is a tool that enables you to render a component in a specific location in the DOM. See its uses, implementation, benefits etc.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/react-portal\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"React Portal - DataFlair\" \/>\n<meta property=\"og:description\" content=\"React portal is a tool that enables you to render a component in a specific location in the DOM. See its uses, implementation, benefits etc.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/react-portal\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-06-16T03:30:53+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-06-16T04:30:24+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-portal.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"React Portal - DataFlair","description":"React portal is a tool that enables you to render a component in a specific location in the DOM. See its uses, implementation, benefits etc.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/react-portal\/","og_locale":"en_US","og_type":"article","og_title":"React Portal - DataFlair","og_description":"React portal is a tool that enables you to render a component in a specific location in the DOM. See its uses, implementation, benefits etc.","og_url":"https:\/\/data-flair.training\/blogs\/react-portal\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-06-16T03:30:53+00:00","article_modified_time":"2023-06-16T04:30:24+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-portal.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/react-portal\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/react-portal\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"React Portal","datePublished":"2023-06-16T03:30:53+00:00","dateModified":"2023-06-16T04:30:24+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/react-portal\/"},"wordCount":667,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/react-portal\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-portal.webp","keywords":["React Portal","React Portals"],"articleSection":["React Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/react-portal\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/react-portal\/","url":"https:\/\/data-flair.training\/blogs\/react-portal\/","name":"React Portal - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/react-portal\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/react-portal\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-portal.webp","datePublished":"2023-06-16T03:30:53+00:00","dateModified":"2023-06-16T04:30:24+00:00","description":"React portal is a tool that enables you to render a component in a specific location in the DOM. See its uses, implementation, benefits etc.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/react-portal\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/react-portal\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/react-portal\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-portal.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-portal.webp","width":1200,"height":628,"caption":"react portal"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/react-portal\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"React Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/react-tutorials\/"},{"@type":"ListItem","position":3,"name":"React Portal"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113483","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=113483"}],"version-history":[{"count":6,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113483\/revisions"}],"predecessor-version":[{"id":113645,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113483\/revisions\/113645"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/113642"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=113483"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=113483"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=113483"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}