I am using React and fetching custom HTML headers and footers to be rendered above and below the main part of the React App (portal). These headers and footers are custom HTML and could be incomplete HTML on their own (but combined they would create complete HTML). For example the header may end in an opening tag like <main>
and the footer could begin with the closing tag </main>
with the portal nested inside.
I have tried to use React’s dangerouslySetInnerHTML, but it seems like it is closing all the tags and not putting the portal in the proper location. For example instead of the header ending in <main>
it ends in <main></main>
. The header, portal, and footer are all on the same level hierarchy in the DOM, instead of the portal being nested between the header’s opening tag and the footer’s closing tags.
basic example of header and footer:
let header = '<h1>Welcome to Our Site</h1>
<main>'
let footer = '</main>
<p>Footer</p>'
This doesn’t work in app.js:
<div dangerouslySetInnerHTML={{__html: portal.headerHtml}}/>
<div id="portalMain">
<AppRoutes/>
</div>
<div dangerouslySetInnerHTML={{__html: portal.footerHtml}}/>
This doesn’t put the portal in between the main tag, it renders the header, portal, and footer all on the same level (portal isn’t nested).
I tried putting the dangerouslySetInnerHTML in its own component, Refs, createPortal, and the parse function from html-react-parser.
What does work is in index.js setting the innerHTML of the root element and having React just handle the App and not using dangerouslySetInnerHTML in App.js:
const rootElement = document.getElementById('root');
rootElement.innerHTML = `
${headerHtml}
<div id="react-root"></div>
${footerHtml}
`;
const reactRootElement = document.getElementById('react-root');
const root = createRoot(reactRootElement);
root.render(<App/>)
There has to be a better way to do this though right? I’ve been chatting with chatGPT and Claude for hours trying to figure out the best way. It seems like the broken HTML header and footer is making it challenging. It would be great if I could get the portal to be in the correct location and have the header and footer within the React App instead of outside of it.
Logan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.