'iFrame is loading index.html instead of local html file specified in the src

I have a React project which consists of many pages.

One page contains an iframe that must load a local HTML file. Instead of that, it loads index.html file (homepage).

I am using "react-router-dom" for route and links.

I think the problem is with redirecting the link of the HTML file to the homepage file.

If this is the problem, how I can disable redirecting to the homepage when calling the desired HTML file?

Edit:

The HTML file is a part of a third-party SDK bundle and can't be converted to a react component.



Solution 1:[1]

If the file is a third party library

Consider putting it in the public directory and using PUBLIC_URL to access the file.

<iframe src=`${process.env.PUBLIC_URL}/bundle/test.htm` ... />

If you need to load another component

Load the component that renders the page directly instead of doing an iframe. That way you are not constrained to path based rules.

If you want path based rules

Consider adding a nested route: https://v5.reactrouter.com/web/example/nesting

Or v6 route: https://reactrouter.com/docs/en/v6/getting-started/overview#nested-routes

Prefer not to intentionally break react-router but work within its constraints.

I would recommend putting an absolute path if it was an external route; however, since it is an internal link it will still conform to react router. Or use public folder.

Solution 2:[2]

See in react app you can only route components. For example, in the app.js of your react application you do

App.js

import { BrowserRouter, Routes, Route, } from 'react-router-dom'
function App(){
   return(
      <BrowserRouter>
        <Routes>
           <Route exact path='/' element={<Your_component />} />
        </Routes>
      </BrowserRouter>
   )
 }

The Problem

In the react you can route through the components according to me. If you try to route another file by writing the URL = 'localhost:3000/another-html-file.html'. It tries to find the URL inside the app.js routes but it is unable to find it and you see it can't find it hence, it always returns the homepage so you only can see the index.html(homepage).

The solution

If you want to route in another HTML file. 1 - Try to build it as a component so it will be easy for the react app to route in it. 2 - Try to set up another route system only for HTML files which might be difficult because your react app always works from the src file containing all the files as JS extensions. I prefer the first one. Hope it might help.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Yash-Sharma2002