Categories
React

react-overlays — Portals and Click Outside

Spread the love

Overlays are something that we have to add often into our React app.

To make this task easier, we can use existing component libraries to add them.

In this article, we’ll look at how to add portals and click outside features into our React app with the react-overlays library.

Portal

We can use the Portal component to lets us render content in the location in the DOM that we want.

For instance, we can use it by writing:

import React, { useRef, useState } from "react";
import Portal from "react-overlays/Portal";

export default function App() {
  const [show, setShow] = useState(false);
  const containerRef = useRef(null);

  let child = <span>But I actually render here!</span>;

  return (
    <div className="flex flex-col items-center">
      <button type="button" className="btn" onClick={() => setShow(true)}>
        Render Child
      </button>
      <div className="bg-brand-200 p-6 rounded-lg shadow my-4">
        <Portal container={containerRef}>{show && child}</Portal>
      </div>
      <div className="bg-brand-200 p-6 rounded-lg shadow " ref={containerRef} />
    </div>
  );
}

We add the button to toggle the show state to show the content of the portal.

The Portal component has the containerRef to set the container for the portal.

This is let us render the portal content in the location of the containerRef .

useRootClose Hook

The useRootClose hook lets us make a component disappear when we click outside it.

To use it, we write:

import React, { useRef, useState } from "react";
import { useRootClose } from "react-overlays";

export default function App() {
  const ref = useRef();
  const [show, setShow] = useState(false);
  const handleRootClose = () => setShow(false);

  useRootClose(ref, handleRootClose, {
    disabled: !show
  });

  return (
    <div className="flex flex-col items-center">
      <button type="button" className="btn" onClick={() => setShow(true)}>
        Show
      </button>

      {show && (
        <div ref={ref} className="rounded shadow bg-white p-6">
          <span>Click anywhere to dismiss</span>
        </div>
      )}
    </div>
  );
}

We add the button to show the div by setting show to true .

Then we add a div that’s shown when show is true .

We pass in the ref to the div to assign it the ref.

Then we pass in that ref to th useRootClose hook to let us remove the container by setting show to false with the handleRootClose function.

We set the disabled property to make it disabled when show is false .

Conclusion

We can add the Portal component to let us add elements to wherever we want in the DOM.

The useRootClose hook lets us remove components whenever we click outside it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *