Handling iframe loading in React
In my most recent project, I needed to utilize a few iframes. Unfortunately, iframes can take a while to load. It’s a pretty bad user experience if an iframe pops onto the screen after a few seconds. Today, I’ll show you how I brought in simple loading animations in React while my iframes load.
For this example we’ll look at my rsvp component. This loads an external google form iframe. First, we’ll add a state of loading to the component that starts out as true.
class Rsvp extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true
};
}render() {
return (
<div className="container rsvp-wrapper">
</div>
);
}
}
Then, we’ll create a hideSpinner function that changes the loading state to false.
class Rsvp extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true
};
}hideSpinner = () => {
this.setState({
loading: false
});
};render() {
return (
<div className="container rsvp-wrapper">
</div>
);
}
}
Then, we’ll add the react-spinkit package. This is a great CSS animations package I’ve used in many projects. We’ll set a ternary that loads the spinner while the iframe is loading.
class Rsvp extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true
};
}hideSpinner = () => {
this.setState({
loading: false
});
};render() {
return (
<div className="container rsvp-wrapper">
{this.state.loading ? (
<Spinner
className="loading text-center"
name="three-bounce"
color="white"
fadeIn="none"
/>
) : null}
</div> );
}
}
Finally, we’ll add the iframe that will call the hideSpinner function onLoad.
class Rsvp extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true
};
}hideSpinner = () => {
this.setState({
loading: false
});
};render() {
return (
<div className="container rsvp-wrapper">
{this.state.loading ? (
<Spinner
className="loading text-center"
name="three-bounce"
color="white"
fadeIn="none"
/>
) : null}
<iframe
src="..."
width="100%"
height="700"
onLoad={this.hideSpinner}
frameBorder="0"
marginHeight="0"
marginWidth="0"
/>
</div>
);
}
}
There we go! We have a clean loading animation for our iframe!