React-router and iframe, browser history

Viewed 7201

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

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

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/

Related