React-router and iframe, browser history
Asked Answered
P

2

15

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

Photoreceptor answered 24/7, 2017 at 9:44 Comment(2)
do the buttons change the url of the main window page?Peripteral
You mean, when I push the url to iframe? No, url stays the same.Photoreceptor
B
14

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} />;
  return iframe;
}
Buffo answered 9/6, 2018 at 7:57 Comment(1)
bad english but yes. iFrame was messing with my router history - until I set a unique key to the iframe for each new time I display it. Would love it if someone gave an explanation as to why this works.Nikolaus
F
3

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/

Flighty answered 4/10, 2021 at 23:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.