I am having a hard time understanding a back navigation issue that occurs in our project.
We are working in a React environment (v17), with react-router-dom (v6) and we render an iframe on a third party service (therefore the iframe src is on a different domain) on our page (the issue happens as well in NextJS).
The page that renders the iframe gets the url from the navigation state (using useLocation() from react-router-dom) and puts that in the iframe src.
When we press the browser back button (or use history.back(), or history.go(-1) in the browser console, or navigate(-1) from the useNavigate hook), nothing happens but the iframe content being reloaded.
No popstate event is being dispatched, and the browser history does not change.
If I hardcode the iframe URL (so no reading the value from some place else), everything works as expected. Also, if I refresh the page, things work fine as well if I press the back button twice (¯\(ツ)/¯)
I've found this interesting article regarding back navigation with React an iframes.
I tried adding a key to the iframe (like Date.now()) but nothing changes.
Here are some sketch components to put things together.
Page 1
const Page1 = () => {
const navigate = useNavigate();
// in our case we are using a GraphQL mutation.
// this is just for demonstration purposes
return <button onClick={() => {
fetchIFrameURLOnTheServer()
.then(url => navigate('/page2', { state: { url } }))
}}>
go to iframe page
</button>
}
Page 2
const Page2 = () => {
const location = useLocation();
const { url } = location.state;
return <iframe src={url} key={Date.now()} />;
}
Router declaration
<BrowserRouter>
<Routes>
<Route element={<Layout />}> // <-- renders the <Outlet />
<Route path='path1' element={Page1}/>
<Route path='path2' element={Page2}/>
</Route>
</Routes>
</BrowserRouter>
I would like to understand what happen and I am seeking some help :P Thank you for your help 🙏