0

I have seen an example like on how to use dangerouslySetInnerHTML().

Here inside the div we are putting some tag (anchor-tag in current example), but I need to insert complete HTML.

Below is the response I am getting via API;

<HTML>
<HEAD>
<BODY>
....
</BODY>
</HEAD>
</HTML>

I already have React Component and corresponding HTML element gets created but after click on the button I would receive above HTML response which will have complete HTML tags i.e HTML tag, body tag etc (it is making some sort of graph).

So, I need to Insert this newly HTML response with the existing HTML.

nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
gsr
  • 69
  • 2
  • 8
  • With "complete HTML" you mean replacing the whole page with the received HTML? – Chris Dec 20 '19 at 09:03
  • yes I need to replace it – gsr Dec 20 '19 at 09:04
  • https://stackoverflow.com/questions/483745/replace-html-page-with-contents-retrieved-via-ajax – Chris Dec 20 '19 at 09:10
  • 1
    I'd have to disagree with the link comment above, don't mix jQuery and React. It's a bad road to go down. – rrd Dec 20 '19 at 09:23
  • You could also set the innerHtml with an iFrame, then the html tags in the response would not be a show blocker. An inline frame is used to embed another document within the current HTML document. https://www.w3schools.com/tags/tag_iframe.asp – Julian Kleine Dec 20 '19 at 11:16

2 Answers2

0

You could use an iframe to show the document. So, if you're fetching the data in an App component, for instance, you could do like this:

const App = () => {

  ... data fetching

  return (
    <iframe src={data} />
  );
}

where the data variable is the data you have fetched from your API endpoint.

0

I have solved the issue using 'dangerouslySetInnerHTML'. The problem I was facing is that i was having the < script > tag as well. So, first I need to remove all the script tag and then again assign it.

 let count = (htmlDataString.toLowerCase().match(/<script/g) || []).length;
 const extractedScriptArray = [];

      for( let i= 0 ; i< count; i++){
        let extractScript = /<script\b[^>]*>([\s\S]*?)<\/script>/gm.exec(x);
        x = x.replace(extractScript[0], "");
        extractedScriptArray.push(extractScript[1]);
      }

      this.setState({ htmlData: x }, () => {
        for (let i = 0; i < count; i++) {
          window.eval(extractedScriptArray[i]);
        }
      });
gsr
  • 69
  • 2
  • 8