Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an external html file with query strings in reactjs

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)?

like image 352
NIsham Mahsin Avatar asked Sep 17 '20 13:09

NIsham Mahsin


People also ask

How do you include external HTML file in react JS?

If you want to include static html in ReactJS. You need to use html-loader plugin if you are using webpack to serve your react code. That is it. Now you can use static html files to load your html files in react.

How do you pass a query parameter in react JS?

To pass in query parameters, we just add them to the Link s to props as usual. For example, we can write the following: We first defined the useQuery Hook to get the query parameters of the URL via the URLSearchParams constructor. We get the useLocation() s search property.

How do I get the URL query parameters in react?

To capture url parameters use window object. You can use "useLocation" from "react-router-dom" instead of window object to achieve same results.

Can you use HTML and react together?

By default, React does not permit you to inject HTML in a component, for various reasons including cross-site scripting. However, for some cases like a CMS or WYSIWYG editor, you have to deal with raw HTML.


1 Answers

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()
like image 128
Mordechai Avatar answered Nov 07 '22 10:11

Mordechai