15
11

More than 3 years have passed since last update.

Reactで画像をlazyloadしつつpreloadするコンポーネント

Last updated at Posted at 2020-02-17

FirstViewにはいらんけど、スクロールして登場するまでにはなるべく存在してほしいみたいな画像があったので作ってみました。
正直こんな雑なやり方で合ってるのか分からんのでもっといい方法知ってる人がいたら教えてください頼みます。


import * as React from 'react';

type Props = {
  imgUrl: string;
  alt: string;
};

export default function LazyAndPreloadImage(props: Props) {
  const [loaded, setLoaded] = React.useState(false);

  React.useEffect(() => {
    // preload しておく
    const img = new Image();
    img.src = props.imgUrl;

    // 読み込めたら img タグ描画する
    img.onload = () => {
      setLoaded(true);
    };
  }, []);

  if (loaded) {
    return <img src={props.imgUrl} alt={props.alt} />;
  }

  // 雑に空divにしてるけど思い思いのplaceholder入れてください
  return <div></div>;
}

15
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
11