What are React Portals?

By Dave Bitter

5 min read

Let's have a look at React Portals and how they can help you in a pinch.

What are React _Portals_?
Authors

Let's dive into an incredibly powerful feature in React that you might not be using yet: React Portals. If you're not familiar with them, don't worry. By the end of this article, you'll not only know what they are but also see why they can be a incredibly useful for your projects!

What are React Portals?

In essence, React Portals provide a way to render children into a DOM node that exists outside the hierarchy of the parent component. Normally, React components are rendered within the confines of their parent components, but with portals, you can render a child component into a different part of the DOM.

schematic showing the NotificationBanner being rendered outside of the normal direct hierarchy

Why is this useful?

Imagine you have a notification banner that needs to be displayed at the top level of your application. This banner should be triggered by various components deep in your component hierarchy. Managing such a requirement can lead to CSS complications and z-index nightmares. React Portals solve this elegantly by allowing these elements to be rendered outside of the parent component's tree, making them easier to manage and style.

How Do React Portals Work?

Using React Portals is quite straightforward. Here's a basic example to get you started with a notification banner.

Creating a Portal

First, you need to create a component that uses a portal. In this case, we'll create a NotificationBanner component:

import React from 'react'
import { createPortal } from 'react-dom'

const NotificationBanner = ({ message }) => {
  return createPortal(
    // component to render
    <div className="notification-banner">{message}</div>,
    // element to render into
    document.body
  )
}

export default NotificationBanner

In this example, we're using createPortal to render the notification banner directly into the document.body, outside of the normal React component tree.

Using the NotificationBanner Component

Now you can use the NotificationBanner component in other parts of your application. Here's an example of how it can be used:

import React from 'react'
import NotificationBanner from './NotificationBanner'

const FooBar = () => {
  return (
    <div>
      <h1>FooBar Component</h1>
      <p>This is the main content of FooBar.</p>
      <NotificationBanner message="This is a notification banner at the bottom of the page!" />
    </div>
  )
}

export default FooBar

In this example, the NotificationBanner is used within the FooBar component, but it will actually render at the bottom of the document.body due to the portal.

Why Should You Use React Portals?

Now that you know how to use React Portals, let's talk about why you should use them.

Better Control Over CSS

By rendering components outside of their parent hierarchy, you gain more control over CSS. No more fighting with z-index issues or complex CSS rules to ensure your notifications appear above other content. Portals allow you to place these elements exactly where you need them in the DOM, making styling much more straightforward.

Improved Accessibility

Portals can help improve the accessibility of your application. By controlling where the component is rendered, you can ensure that it appears in a logical order in the DOM, making it easier for screen readers and other assistive technologies to navigate. This is particularly useful for modal dialogs and other overlay components.

Simplified Event Handling

When components like notifications are rendered outside of the parent component, it simplifies event handling. You no longer need to worry about event propagation issues that can arise from deeply nested component structures. Events will still bubble up as expected, maintaining React's synthetic event system.

Maintaining React Virtual DOM Hierarchy

Another important use case for React Portals is when you need a component to be a child in the React virtual DOM but not in the actual DOM. This is useful in scenarios where the component needs to maintain its logical relationship with its parent for state management or context purposes but needs to be visually or structurally placed elsewhere in the DOM.

Flexibility in Component Design

React Portals offer great flexibility in how you structure your components. You can keep the logic for triggering a portal in one component while rendering the actual content elsewhere in the DOM. This separation of concerns can lead to cleaner, more maintainable code, especially for complex UI elements.

Perfect for Third-Party Integrations

If you're working with third-party libraries or legacy code, Portals can be incredibly helpful. They allow you to inject React components into any part of the DOM, even outside your main React app. This makes integrating React with other technologies much smoother.

Conclusion

React Portals are a powerful feature that elegantly solves common UI challenges, especially when dealing with elements that need to break out of their component hierarchy. They're particularly useful for creating overlays, modals, tooltips, and notification banners that need to be rendered at the root level of your DOM.

By using Portals, you can simplify your CSS management, improve accessibility, and maintain a cleaner component structure. They're not about making complex UI elements, but rather about making it easier to manage where your components render in the DOM.

Remember, Portals are a tool in your React toolkit. While they're incredibly useful in certain situations, they're not needed for every component. Use them when you need to render content outside of the normal component tree, and you'll find they can greatly simplify your code and improve your application's structure.

Now that you understand React Portals, consider where they might be useful in your current or future projects. You might be surprised at how often this simple concept can lead to cleaner, more maintainable code. Happy coding!


Upcoming events

  • The Test Automation Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! 🚀🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🍻 Drinks 21:00 – 🙋‍♀️ See you next time? First Round of Talks: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian Würthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Test Automation Meetup
  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiënte applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Talk 1 20:00 – 🍹 Kleine pauze 20:15 – 📢 Talk 2 21:00 – 🙋‍♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Winter `24 edition
  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tütüncü, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – 📢 Event-Driven Microservices - Beyond the Fairy Tale 21:00 – 🙋‍♀️ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many “microservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design

Share