6

I have an html file and it accepts few query strings

Html file also contains css and script included using script tag

ie we can call this html file as below

external.html?param='something'

i have to use this html in a react component and return as JSX. currently i have done returning as an Iframe as below

const Component = () => {
    const iframeUrl = `external.html?param='something'`;
    return (
        <iframe
            {...props}
            src={iframeUrl}
        />
    )
}

but how can i do without using iframe or iframe with local html(should not download html from server all the time)?

NIsham Mahsin
  • 340
  • 5
  • 18

1 Answers1

3

You cannot just import an HTML document as a react component. Iframes are just for that.

To import a local html file as an iframe without constantly requesting a remote resource you should paste the file content into the iframe's srcdoc attribute which is an alternative to src for inline html.

Keep in mind though that the html will still be transmitted on a reload, just together with the rest of the app instead of in a separate request. For real caching you'll have to utilize the local storage mechanisms et al.

With this in place, you can then manipulate the query params:

// iframe inside a react ref
frameRef.current.contentWindow.location.href += 'myQueryParams'

You can also refresh the frame (it preserves the params):

frameRef.current.contentWindow.location.reload()
Mordechai
  • 15,437
  • 2
  • 41
  • 82
  • srcdoc seems not working. For the clarity what i exactly need is i want to load `https://mozilla.github.io/pdf.js/web/viewer.html` in in iframe (this viewer is hosted in my server) .but this html should not request remote html file i am setting iframe with the above url and passing below query param file=blob:https://abc.abc.com/c7ac784c-0845-4fc0-b98d-73c66673ba6d#page=1&zoom=auto,-89,842 – NIsham Mahsin Sep 21 '20 at 06:18
  • I missed the query string part in the question. Let me think... – Mordechai Sep 21 '20 at 09:21
  • Are the queries handled in the html at client side (using the History API) or server side? I assume the former – Mordechai Sep 21 '20 at 09:23
  • from client side. – NIsham Mahsin Sep 21 '20 at 16:19
  • @NIshamMahsin Updated my answer, let me know if it helps. – Mordechai Sep 21 '20 at 20:40