Eddie Lam
Eddie Lam

Reputation: 619

How to suspense the whole component before the image inside is loaded?

I have the following component: In this component, there is an image. When I load the page, I realize the page will be loaded first then the image will be loaded later. How can I suspense the whole page before the image is loaded? I have tried to wrap the whole div (id="container") in a Suspense component with a fallback method but it doesn't seem to work on images, and only on components.

How can I suspense the whole component before the image inside is loaded?

import React from "react";
import resume from "../assets/Joe_Rogan_Resume.jpg";
import Banner from "./Banner";

const Resume = () => (
  <div id="container">
    <Banner styleclass="ResumePageBanner" h1text="My Resume" />
    <div className="resumePage">
      <div id="resume">
        <img src={resume} alt="Resume" />
      </div>
    </div>
  </div>
);

export default Resume;

Upvotes: 3

Views: 3008

Answers (1)

Hossein Moradi
Hossein Moradi

Reputation: 598

The Suspense component in React 16.x only lets you wait for some code to load, not any type of data (including images). Suspense for data fetching is still experimental. So you need to handle it manually if you don't want to use an unstable version.

import React from "react";
import resume from "../assets/Joe_Rogan_Resume.jpg";
import Banner from "./Banner";

const Resume = () => {
  const [isImageLoaded, setIsImageLoaded] = React.useState(false);

  React.useEffect(() => {
    const image = new Image();
    image.onload = () => setIsImageLoaded(true);
    image.src = resume;

    return () => {
      image.onload = null;
    };
  }, []);

  if (!isImageLoaded) {
    return null;
  }

  return (
    <div id="container">
      <Banner styleclass="ResumePageBanner" h1text="My Resume" />
      <div className="resumePage">
        <div id="resume">
          <img src={resume} alt="Resume" />
        </div>
      </div>
    </div>
  );
}

export default Resume;

Upvotes: 3

Related Questions