Friday, April 15, 2022

[FIXED] How do you reload an iframe with ReactJS?

Issue

My ReactJS component contains an iframe. In response to an event in the outer page, I need to reload the iframe. If the user has navigated to another page in the iframe, I need to reset it to the URL that it had when I first loaded the page. This URL is available in this.props.

I've tried using forceUpdate(). I can see that this causes the render method to run, but the iframe doesn't get reset - presumably because React can't tell that anything has changed.

At the moment I'm appending some random text to the iframe's querystring: this URL change forces React to re-render the iframe. However this feels a bit dirty: the page within the iframe is beyond my control so who knows what this extra querystring value might do?

resetIframe() {
    console.log("==== resetIframe ====");
    this.forceUpdate();
}

public render() {
    console.log("==== render ====");

    // How can I use just this.props.myUrl, without the Math.random()?
    let iframeUrl = this.props.myUrl + '&random=' + Math.random().toString();

    return <div>
        <button onClick={() => { this.resetIframe(); }}>Reset</button>
        <iframe src={iframeUrl}></iframe>
    </div>
}

(I'm using TypeScript too, if that makes a difference.)


Solution

I'd create a state variable with the random, and just update it on resetIframe:

state = {
     random: 0
}
resetIframe() {
    this.setState({random: this.state.random + 1});
}

public render() {
    return <div>
        <button onClick={() => { this.resetIframe(); }}>Reset</button>
        <iframe key={this.state.random} src={this.props.myUrl}></iframe>
    </div>
}

Here is a fiddle working: https://codesandbox.io/s/pp3n7wnzvx



Answered By - Diogo Sgrillo
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.