Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router and iframe, browser history

I came to the kind of anyoing problem. So, I have a component in react and also using react-router. Everything works almost great. This component has a list of items, when you click on one, it pushes url to the iframe[src={url}]. And here appears the problem, if I will click on several items and then click on the previous page/back button, instead of going to the previous page, it just shows the previous iframe of url that was pushed to iframe.

What do I do in this situation?

@I'm using react-router-dom v4

like image 846
bunakawaka Avatar asked Jul 24 '17 09:07

bunakawaka


People also ask

Does React Router use history API?

React Router uses the history package, which builds on the browser history API to provide an interface to which we can use easily in React apps. location - (object) The current location. May have the following properties: pathname - (string) The path of the URL.

Do iframes work in React?

In React, developers use iframes to create either a sandboxed component or an application that is isolated from its parent component. In an iframe, when a piece of content is embedded from an external source, it is completely controlled by the source instead of the website it is embedded in.


2 Answers

Don't just change the src. You've to replace a new iframe everytime the src change. By doing that without change things much, just add difference key to your iframe everytime you change src

render(){
const iframe = <iframe key={this.thing.id} src={this.thing.src} ></iframe>
return(iframe)
}
like image 108
Expl0de Avatar answered Sep 19 '22 13:09

Expl0de


Just to add to @Expl0de answer,

You should add a unique value to the key attribute, which will change from src to src, each time the iframe is reused.

The issue happens because an iframe changing the src attribute is considered as content navigation, being pushed to the window.history browser stack. When you go back in the browser navigation it just loads the same page, same iframe with a different src attribute.

When adding a key prop that changes on different src values, React will unmount and remount this iframe element, because it is not the "same element" anymore. This will prevent the iframe from changing the browser's history.

A more in-depth explanation, covering React's Reconciliation Process and examples, can be found here: https://www.aleksandrhovhannisyan.com/blog/react-iframes-back-navigation-bug/

like image 32
Isaque Hofmeister de Azevedo Avatar answered Sep 17 '22 13:09

Isaque Hofmeister de Azevedo