CreatePortal SSR: Building Server-Side Rendered Portals in React

ian hardy
5 min readAug 28, 2023

--

Server-Side Rendering (SSR) is a powerful technique in web development that enhances the performance and SEO-friendliness of your React applications. However, when it comes to complex user interfaces, incorporating features like modals, tooltips, or popovers can be challenging in SSR environments. Enter CreatePortal: a React feature that enables the creation of Server-Side Rendered Portals, allowing you to render these complex UI components seamlessly. In this comprehensive guide, we will explore CreatePortal SSR, understand its significance, implementation, and best practices.

portal
Photo by Damian Zaleski

Understanding Server-Side Rendering (SSR)

Before diving into CreatePortal SSR, let’s briefly understand the concept of Server-Side Rendering. In traditional Single-Page Applications (SPAs), the client browser fetches an empty HTML file and subsequently fills it with JavaScript-generated content. While this approach offers interactivity, it can result in slower initial load times and challenges for search engine optimization (SEO).

SSR, on the other hand, involves rendering the initial HTML content on the server, which is then sent to the client browser. This approach improves performance by reducing the time it takes for the user to see content and enhances SEO as search engines can crawl the pre-rendered HTML.

The Challenge of Complex UI Components in SSR

While SSR offers many benefits, it introduces complexities when dealing with components like modals or tooltips, which may rely on client-side rendering and the Document Object Model (DOM). In SSR, these components might not work as expected due to the server-rendered HTML not having access to the client’s DOM.

This is where CreatePortal comes into play, providing a solution to render complex UI components on both the server and the client seamlessly.

What is CreatePortal?

CreatePortal is a feature in React that allows you to render a component’s children in a different part of the DOM hierarchy. This feature is particularly useful for rendering elements outside the parent component’s DOM tree. While it’s commonly used for modals and overlays in client-side rendering (CSR), it can also be harnessed for SSR.

In SSR, CreatePortal allows you to render components on the server but have them attached to the client’s DOM when the JavaScript bundle is hydrated. This process ensures that complex UI components, like modals or tooltips, function correctly in an SSR environment.

Implementing CreatePortal SSR

Let’s walk through the process of implementing CreatePortal SSR step by step:

1. Setting Up Your Project

First, make sure you have a React project set up with SSR. Popular libraries like Next.js simplify this process significantly.

2. Import React and ReactDOM

Ensure you have React and ReactDOM installed in your project. Import them into the file where you plan to use CreatePortal.

import React from 'react';
import ReactDOM from 'react-dom/server';

3. Create Your Portal Component

Create a component that represents the content you want to render as a portal. For instance, let’s create a simple modal:

function Modal(props) {
return (
<div className="modal">
<div className="modal-content">{props.children}</div>
</div>
);
}

4. Define a Portal Container

Next, define an element on the server to act as the container for your portal content. You can create a new div element or use an existing one.

const portalContainer = document.createElement('div');
portalContainer.setAttribute('id', 'portal-container');

5. Server-Side Rendering

In your SSR code, use ReactDOM’s renderToString method to render your portal component and the portal container. Add this to your SSR route handler:

const portalHtml = ReactDOM.renderToString(
<div>
<App />
{ReactDOM.createPortal(<Modal>Portal Content</Modal>, portalContainer)}
</div>
);

6. Send the Rendered HTML to the Client

Finally, send the rendered HTML, including the portal content, to the client in the response:

res.send(`
<!DOCTYPE html>
<html>
<head>
<!-- Your head content here -->
</head>
<body>
<div id="root">${portalHtml}</div>
<div id="portal-container"></div>
</body>
</html>
`);

7. Hydrate the Portal on the Client

In your client-side JavaScript code (usually in your entry file, like index.js), use ReactDOM's hydrate method to attach the portal to the client's DOM:

import ReactDOM from 'react-dom';
import App from './App';
const portalContainer = document.getElementById('portal-container');
ReactDOM.hydrate(<Modal>Portal Content</Modal>, portalContainer);

With this setup, your modal (or other portal content) will be correctly rendered on both the server and the client, ensuring that it functions seamlessly in SSR environments.

react
Photo by Caspar Camille Rubin

Best Practices for CreatePortal SSR

When implementing CreatePortal SSR, it’s essential to follow best practices to ensure a smooth and optimized user experience. Here are some best practices to consider:

  1. Use Portals Sparingly: While CreatePortal is a powerful tool, use it judiciously. Only apply it to components that genuinely require client-side rendering, such as modals, tooltips, or popovers. Overusing portals can complicate your code and negatively impact performance.
  2. Proper Styling: Ensure that styles for React portal components are loaded correctly on both the server and the client. This may involve using CSS-in-JS solutions like styled-components or importing stylesheets. Consistent styling ensures that your portal components look and behave the same way across environments.
  3. SEO Considerations: Keep search engine optimization (SEO) in mind when using portals. Search engine crawlers primarily see the initial server-rendered HTML. Ensure that important content, including the content within portals, is present in this initial HTML to improve SEO.
  4. Test Extensively: Rigorously test your CreatePortal SSR implementation. Verify that portal components work as expected in different environments and devices. Pay special attention to edge cases and ensure that user interactions with portals are consistent.
  5. Performance Optimization: Be mindful of performance implications when using portals, especially for large or frequently appearing ones. Consider implementing performance optimizations, such as lazy loading portal content when it’s not immediately needed. Profile your application to identify and address performance bottlenecks.
  6. Accessibility: Ensure that portal components maintain accessibility standards. Screen readers and other assistive technologies should be able to interact with and provide information about portal content. Test your portal components with accessibility tools and guidelines in mind.
  7. Server-Side Data Fetching: If your portal components require data fetching, handle data retrieval on the server as much as possible. This ensures that the initial server-rendered HTML contains the necessary data, improving performance and SEO.
  8. Error Handling: Implement robust error handling for portal components. Consider scenarios where portal content fails to load or render correctly and provide graceful error handling mechanisms for users.

Conclusion

CreatePortal SSR is a valuable tool for addressing the challenges of rendering complex UI components in Server-Side Rendered React applications. By leveraging the power of CreatePortal, you can seamlessly render components like modals, tooltips, or overlays on both the server and the client, ensuring a consistent user experience and improved SEO.

Understanding the implementation of CreatePortal SSR involves setting up your project, creating portal components, defining portal containers, rendering content on the server, and hydrating portals on the client. Following best practices, such as using portals sparingly and considering SEO, ensures that your SSR-powered portals work efficiently and effectively.

When it comes to React development and hire ReactJS developers, having an expert team by your side can make all the difference. CronJ is a renowned software development company with a strong focus on React development and a proven track record of delivering top-quality solutions to clients worldwide.

References

  1. https://www.searchenginejournal.com/server-side-rendering/481581/
  2. Context API in React JS
  3. Best Redux Middleware
  4. Diff Algorithm in React
  5. Why Are Parent Components in React Important? | Stackademic

--

--

ian hardy
ian hardy

Written by ian hardy

My name is Ian Hardy and I am a Developer.

Responses (1)