React Portal inserting content multiple times

1.3k Views Asked by At

Created a React portal and it works well except that it renders the requested content into the portal twice.

enter image description here

It also seems to run the function that inserts the content many times:

enter image description here

import React from "react";
import ReactDOM from "react-dom";
import PropTypes from "prop-types";

export default function Portal({
  id
}) {
  console.log("Inserting into portal");
  return (
    <>
      {ReactDOM.createPortal(
        <div>MY REACT CONTENT</div>,
        window.document.getElementById(`portal-${id}`)
      )}
    </>
  );
}

ProductPrice.propTypes = {
  id: PropTypes.number.isRequired,
};

How can I structure this file to ensure that the portal is only created once?

1

There are 1 best solutions below

0
On

I believe the component where you are using Portal is being re-rendered resulting Portal being re-rendered. You can wrap your Portal with React.memo() and that might solve it,