How to "inject" React client components into plain HTML files?
Unanswered
Serengeti posted this in #help-forum
SerengetiOP
Say you have a plain HTML file, could be a fragment, not in necessarily a complete document. Say it's stored in your Next.js project, fetched from a website, or something like that.
How can I read/parse this plain HTML file in a server component, replace/wrap certain elements with React client components, and then render it and serve it to the browser in a way that the HTML comes out as HTML, and the React client components gets hydrated and such properly?
I know I can use dangerously set html to render HTML, but I don't want to just display the "dead" HTML. I want to inject dynamic React components into it that will work as normal React components, with access to contexts and everything else a component would.
Say for example there's a
How can I read/parse this plain HTML file in a server component, replace/wrap certain elements with React client components, and then render it and serve it to the browser in a way that the HTML comes out as HTML, and the React client components gets hydrated and such properly?
I know I can use dangerously set html to render HTML, but I don't want to just display the "dead" HTML. I want to inject dynamic React components into it that will work as normal React components, with access to contexts and everything else a component would.
Say for example there's a
<video> tag and I want to replace/wrap it with a dynamic React-based video player, or I want to replace all <a> tags with <Link> components.2 Replies
@Serengeti Say you have a plain HTML file, could be a fragment, not in necessarily a complete document. Say it's stored in your Next.js project, fetched from a website, or something like that.
How can I read/parse this plain HTML file in a server component, replace/wrap certain elements with React client components, and then render it and serve it to the browser in a way that the HTML comes out as HTML, and the React client components gets hydrated and such properly?
I know I can use dangerously set html to render HTML, but I don't want to just display the "dead" HTML. I want to inject dynamic React components into it that will work as normal React components, with access to contexts and everything else a component would.
Say for example there's a `<video>` tag and I want to replace/wrap it with a dynamic React-based video player, or I want to replace all `<a>` tags with `<Link>` components.
you can import the html as a raw string
then use something like https://www.npmjs.com/package/html-react-parser to parse it with suitable options like
then use something like https://www.npmjs.com/package/html-react-parser to parse it with suitable options like
replace, see the documentation of the library for more details