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)?
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.
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.
To capture url parameters use window object. You can use "useLocation" from "react-router-dom" instead of window object to achieve same results.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With