1

Consider the following simple React component that displays a YouTube video and has a button to change the video:

import React from 'react';
import ReactDOM from 'react-dom';

class Video extends React.Component {
  state = { video: 'G8KpPw303PY' };

  handleClickButton = event => {
    this.setState({ video: 'PHAc3_MEjgQ' });
  };

  render() {
    return (
      <div>
        <iframe
          src={`https://www.youtube.com/embed/${this.state.video}?autoplay=1`}
        />
        <input
          type="button"
          value="Change Video"
          onClick={this.handleClickButton}
        />
      </div>
    );
  }
}

ReactDOM.render(<Video />, document.getElementById('react-root'));

If I were to click on the button, the video changes (as it should). However, a page is also added to the browser history. How do I make it so a page is not added to the browser history?

I understand that to load a new URL in an iframe in vanilla JavaScript, we'd use iframe.contentWindow.location.replace('url'). Due to React's declarative/functional nature though, doing something like that seems really hacky, and I understand there would need to be built-in support for something like this.

1
  • Can you explain what you mean by "a page is added to the browser history"? Is it affecting the forward/back buttons? Or is the issue just that the browser knows it's been there (eg. it may be listed if you go to about:history)? The latter seems like a feature I can't think of a good reason to bypass. If you explain why this is an issue it might also help us to suggest alternate solutions. Commented Sep 10, 2016 at 2:39

1 Answer 1

0

You might consider entirely replacing your embedded URL <iframe src={url/${url.component}?}/> with the entire iframe.

You could use code like

var MyComponent = React.createClass({/*...*/});
var myElement = <iframe src="https://www.youtube.com/embed/G8KpPw303PY"></iframe>;
React.render(myElement, document.getElementById('example'));
<!-- where this is rendered 'on top of' or replacing your old video -->

[source] and more detail if this strikes your fancy

to add an iFrame element that, per this method, already exists in the page.

Alternatively, if you only care specifically about the previous page iteration appearing in the history, you could implement this workaround. It does exactly that, though it's also hacky.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.