How to Make React Portal Work with React Hooks?

Sometimes, we want to make React Portal work with React Hooks.

In this article, we’ll look at how to make React Portal work with React Hooks.

Make React Portal Work with React Hooks

To make React Portal work with React Hooks, we can create a portal component with the ReactDOM.createPortal method.

For instance, we write:

import React from "react";
import ReactDOM from "react-dom";

export const Portal = ({
  children,
  className = "root-portal",
  element = "div"
}) => {
  const [container] = React.useState(() => {
    const el = document.createElement(element);
    el.classList.add(className);
    return el;
  });

  React.useEffect(() => {
    document.body.appendChild(container);
    return () => {
      document.body.removeChild(container);
    };
  }, [container]);

  return ReactDOM.createPortal(children, container);
};

export default function App() {
  return (
    <div>
      <Portal>hello world</Portal>
    </div>
  );
}

We create the Portal component that takes the children, className, and element props.

In it, we create the container element with the useState hook.

We pass in a function that calls docuemnt.createElement and returns the element that’s created.

We take the element prop to create the element and so we create a div by default.

Also, we call el.classList.add to add the class attribute to the element and set it to className.

Then in the useEffect hook callback, we call document.body.appendChild to append the container to the body.

And then we return the portal created with ReactDOM.createPortal created with children and container.

In App, we use Portal to add a div into the body element.

Conclusion

To make React Portal work with React Hooks, we can create a portal component with the ReactDOM.createPortal method.