What are React Portals?
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.
- Authors
- Name
- Dave Bitter
- linkedinDave Bitter
- twitter@dave_bitter
- Github
- githubDaveBitter
- Website
- websiteBlog
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.
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
Drupal CMS Launch Party
Zoals sommigen misschien weten wordt op 15 Januari een nieuwe distributie van Drupal gelanceerd. Namelijk Drupal CMS (ook wel bekend als Starshot). Om dit te vieren gaan we op onze campus een klein eventje organiseren. We gaan die dag samen de livestream volgen waarbij het product gelanceerd wordt. De agenda is als volgt: 17u β 18u30: Drupal CMS livestream met taart 18u30 β 19u00: Versteld staan van de functionaliteiten 19u β 20u: Pizza eten en verder versteld staan van de functionaliteiten Laat ons zeker weten of je komt of niet door de invite te accepteren! Tot dan!
| Coven of Wisdom Herentals
Go to page for Drupal CMS Launch PartyCoven of Wisdom - Herentals - Winter `24 edition
Worstelen jij en je team met het bouwen van schaalbare digitale ecosystemen of zit je vast in een props hell met React of in een ander framework? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en flexibele 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 β π’ Building a Mature Digital Ecosystem - Maarten Heip 20:00 β πΉ Kleine pauze 20:15 β π’ Compound Components: A Better Way to Build React Components - Sead Memic 21:00 β πββοΈ Drinks 22:00 β π» Tot de volgende keer? Tijdens deze meetup gaan we dieper in op het bouwen van digitale ecosystemen en het creΓ«ren van herbruikbare React componenten. Maarten deelt zijn expertise over het ontwikkelen van een volwassen digitale infrastructuur, terwijl Sead je laat zien hoe je 'From Props Hell to Component Heaven' kunt gaan door het gebruik van Compound Components. Ze delen praktische inzichten die je direct kunt toepassen in je eigen projecten. π Waar? Je vindt ons bij iO Herentals - Zavelheide 15, Herentals. Volg bij aankomst de borden 'meetup' vanaf de receptie. π« Schrijf je in! De plaatsen zijn beperkt, dus RSVP is noodzakelijk. Dit helpt ons ook om de juiste hoeveelheid eten en drinken te voorzien - we willen natuurlijk niet dat iemand met een lege maag naar huis gaat! π 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 editionThe 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? Overcoming challenges in Visual Regression Testing - Sander van Surksum, Pagespeed | Web Performance Consultant and Sannie Kwakman, Freelance Full-stack Developer How can you overcome the challenges when setting up Visual Regression Testing? 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