Created a React portal and it works well except that it renders the requested content into the portal twice.
It also seems to run the function that inserts the content many times:
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?
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,