How to create Portals in GatsbyJS

January 06, 2020

Image from instagram

In previous post, we discussed what’s a portal in React and where and how to use them. Now we’ll see how to create one in GatsbyJS. Refer that article to know what a portal is and how its used. This article covers only its implementation in GatsbyJS framework.

Using Portals in GatsbyJS

In Gatsby, we don’t don’t create an index.html file. It’s created by Gatsby on compile time and we have little control to edit it directly. Instead, we will write the code to create our DOM element in gatsby-ssr.js file and Gatsby will compile it for us and create our DOM element.

Creating the portal DOM element

Add the following code in your gatsby-ssr.js file:

import React from 'react';

('use strict');

export const onRenderBody = ({ setPostBodyComponents }, pluginOptions) => {
  setPostBodyComponents([
    <div
      key={pluginOptions.key ? pluginOptions.key : 'my-portal'}
      id={pluginOptions.id ? pluginOptions.id : 'my-portal'}
    >
      {pluginOptions.text}
    </div>,
  ]);
};

Build your project and you’ll notice the newly created DOM element: The div#my-root is our portal now.

Rendering a component in our portal

Let’s create a full screen image viewer component which we will render in our portal. The code for the component will be something like this:

const ImageViewer = ({ image, isOpen, onClose }) => {
  return isOpen
    ? createPortal(
        <div className="modal">
          <div className="image-container-modal">
              <Image fluid={image.photo.childImageSharp.fluid} />
            </div>
          </div>
          <button onClick={onClose} type="button">
            Close
          </button>
        </div>,
        document.getElementById('portal'),
      )
    : null;
};

export default ImageViewer;

Written by Gagandeep Rangi who likes to talk about himself in third person. Twitter Instagram

Email icon