Home > Mobile >  How can I inject HTML fetched from the back end into a react component?
How can I inject HTML fetched from the back end into a react component?

Time:12-30

I would like to host some HTML on my back end that I can then insert into a react component.

I've tried solutions that involve using dangerouslySetInnerHTML, but those are equally unsuccessful.

The basic idea is that I want to have a component, Content, that fetches some HTML and then returns a fragment with that HTML in it:

export async function Content({ resourcePath }) {
  const response = await fetch(resourcePath, { method: 'GET' })
  const html = await response.text();

  return (
    <>
      {html}
    </>
  )
}

On the back end, I have routes set up on an Express server listening for GET requests on resourcePath:

import express from 'express';
import fs from 'fs';

export const contentRouter = express.Router();

contentRouter.get('/content/homepage', (_, res) => {
  const data = fs.readFileSync("path/to/page.html");
  res.send(data.toString());
})

When I load a page that contains a Content component I'm able to log the raw HTML from the response, but the console barfs a ton of errors.

The error that I believe is most relevant is

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

I suspect that the problem has something to do with Promises, namely that as my code is currently written the Content component tries to return a fragment that contains a Promise and not the resolved value.

If that's the case, how can I set the inner HTML of Content to the HTML returned from the fetch?

CodePudding user response:

Have you tried this https://www.npmjs.com/package/html-react-parser ?

Not sure if parsing would be what you're looking for

CodePudding user response:

You could use dangerouslySetInnerHTML prop on element , see docs for more info https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

 export async function Content({ resourcePath }) {
  const response = await fetch(resourcePath, { method: 'GET' })
  const html = await response.text();

  return (
    <div dangerouslySetInnerHTML={{__html:html  }} />
  )
}
  • Related