DEV Community

Cover image for React - Portals
Nicolas B.
Nicolas B.

Posted on • Updated on

React - Portals

In the world of React, creating dynamic user interfaces is a common requirement. Sometimes, you need to render components outside of their parent hierarchy or create overlays like modals or tooltips. In such cases, React Portals come to the rescue. In this tutorial, we'll dive into React Portals, understanding what they are and how to use them effectively to build dynamic and versatile UI components.


What are React Portals?

Imagine you have a React component deep within your component tree, but you want to render something from that component at the top level of your DOM hierarchy. This is where React Portals shine. React Portals provide a way to render a component's children in a different part of the DOM tree, outside of the parent's hierarchy.


Advantages of React Portals

  • Isolation: Portals allow you to isolate certain UI components from the rest of your application, making it easier to manage complex UI scenarios.

  • Layering: You can create overlays, modals, and tooltips that appear on top of other content, without being constrained by the component hierarchy.

  • Accessibility: Portals enable you to improve the accessibility of your UI by rendering content where it makes the most sense in the DOM.

  • Clean Code: Portals help keep your component logic clean and focused, as you can separate UI rendering concerns from the parent component.


Practical Case

Let's dive into a practical example of using React Portals to create a modal component.

Step 1 : Make a modal component

// Modal.js

import React, { useEffect, useState } from 'react'
import ReactDOM from 'react-dom'

const rootPortal = document.getElementById('modal-root')

export const Modal = ({ children }) => {
  const [isOpen, setIsOpen] = useState(false)

  // add open and close modal logic

  return ReactDOM.createPortal(
    <div>
      <h1>My modal</h1>
    </div>,
    rootPortal
  )
}
Enter fullscreen mode Exit fullscreen mode

In this code, we create a Modal functional component that uses React Portals. It renders its children into a separate DOM node (rootPortal) outside the normal React component hierarchy.

Step 2 : Setup the portal

Now, let's use our Modal component in another part of our application.

To do this, we need to place our tag with the correct id at the top of our application. In the case of an app react, we could place it in the index.js here:

// index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <div className="modal-root"/>
    <App />
  </React.StrictMode>
);

reportWebVitals();
Enter fullscreen mode Exit fullscreen mode

Step 3 : Use the Modal component

Now, let's use our Modal component in another part of our application:

// Profile.js

export const Profile = () => {
  return (
    <div className="profile">
      <img src={profilePicture} className="profile-picture" alt="logo" />
      <div className="profile-name">Your Name</div>
      <div className="profile-bio">Your Bio</div>
      <Modal>
        <h1>My content</h1>
      </Modal>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

In this case, our Modal will be teleported in the top of our app, below the <App />.


Conclusion

React Portals provide a powerful way to render components outside of their parent hierarchy, enabling you to create dynamic and versatile user interfaces. Whether you're building modals, tooltips, or other overlay components, React Portals are a valuable tool in your React development toolkit.

By mastering React Portals, you can enhance the user experience of your applications and create more interactive and engaging UIs. So, go ahead, experiment with React Portals, and unlock new possibilities for your React projects.

If you enjoyed this tutorial, please consider following me for more helpful content. Your support is greatly appreciated! Thank you!

Happy coding!

Top comments (4)

Collapse
 
tehawanka profile image
Bartek Mendecki

Short and clean explanation, nice.
Just there is a typo <Modale> instead of <Modal>

Collapse
 
brdnicolas profile image
Nicolas B.

I fixed that, thank's for your feedback :)

Collapse
 
luka_brouard_7c90194e8fd1 profile image
Luka Brouard

very nice second article bro, continue like this bro,

spike down.

Collapse
 
zagriyen profile image
zagriyen

Very interesting article, keep it up.