Understanding Portals and Use Cases in React JS

Introduction

In React, portals provide a way to render children components into a DOM node that exists outside the parent component's DOM hierarchy. This can be useful for creating modals, tooltips, and other UI elements that need to escape the parent container's styles or overflow restrictions. In this tutorial, we will explore how portals work in React, with examples and use cases.

What is a Portal in React?

A portal allows you to render a child component into a different part of the DOM, outside its parent hierarchy. React provides the ReactDOM.createPortal method to facilitate this.

Syntax:


  ReactDOM.createPortal(child, container)
      

Where:

  • child: The React element you want to render.
  • container: The DOM node where the child should be rendered.

Step 1: Basic Example of Using Portals

Let's start with a simple example of using a portal in a React component. We'll render a modal outside the main application div.


  import React from 'react';
  import ReactDOM from 'react-dom';
  
  function Modal() {
      return (
          

This is a modal

Content goes here...

); } function App() { return (

Welcome to the React App

{/* Rendering Modal outside the normal DOM hierarchy using Portal */} {ReactDOM.createPortal( , document.getElementById('portal-root') )}
); } export default App;

In this example, the modal is rendered into a div with the id portal-root outside the main DOM hierarchy of the App component.

Step 2: Setting up the HTML Structure

For the above portal to work, you need to ensure that there is a DOM node where the portal content will be rendered. In the public/index.html file, add the following div:


  
  

This portal-root div will serve as the container where the modal is rendered via the portal.

Step 3: Handling Events in Portals

Portals allow you to attach event listeners to components rendered outside their usual DOM hierarchy. For example, you might want to close the modal when clicking outside of it.


  import React, { useState } from 'react';
  import ReactDOM from 'react-dom';
  
  function Modal({ onClose }) {
      return (
          

This is a modal

Click anywhere outside this box to close the modal.

); } function App() { const [isModalOpen, setModalOpen] = useState(false); const openModal = () => setModalOpen(true); const closeModal = () => setModalOpen(false); return (

Welcome to the React App

{isModalOpen && ReactDOM.createPortal( , document.getElementById('portal-root') )}
); } export default App;

In this example, the Modal component has a close button. The modal is displayed when the Open Modal button is clicked. You can enhance this by adding functionality to close the modal when the user clicks outside of it.

Step 4: Use Case - Tooltips

Portals can also be used for creating tooltips, where the tooltip content is rendered outside of the parent component's overflow and clipping constraints.


  import React, { useState } from 'react';
  import ReactDOM from 'react-dom';
  
  function Tooltip({ text }) {
      return (
          
{text}
); } function App() { const [showTooltip, setShowTooltip] = useState(false); return (

Hover over the button to see the tooltip

{showTooltip && ReactDOM.createPortal( , document.body )}
); } export default App;

In this case, the Tooltip component is rendered outside the button's normal DOM hierarchy by using the portal, ensuring it appears above other content regardless of its parent container.

Step 5: Use Case - Modals

Modals are another common use case for portals. Portals allow modals to be rendered outside the usual flow, making them easier to overlay on top of other UI elements without being constrained by parent styles.


  import React, { useState } from 'react';
  import ReactDOM from 'react-dom';
  
  function Modal({ onClose }) {
      return (
          

This is a modal

); } function App() { const [isModalOpen, setModalOpen] = useState(false); const openModal = () => setModalOpen(true); const closeModal = () => setModalOpen(false); return (

Welcome to the React App

{isModalOpen && ReactDOM.createPortal( , document.getElementById('portal-root') )}
); } export default App;

This example demonstrates how a modal can be displayed using a portal. The modal is rendered into the portal-root div, allowing it to overlay other content in the application.

Conclusion

React portals are a powerful feature that enable rendering child components outside the normal DOM hierarchy. They are useful for use cases such as modals, tooltips, and other UI elements that require positioning or behavior outside of their parent component's constraints. By using portals, you can improve the flexibility and usability of your React applications.





Advertisement