0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

起こったこと

input要素に渡された画像をFileReaderで読み込んでプレビュー表示させる機能を作っていました。
画像をアップロードすると以下のエラーが出ました。

Error: Image with src (中略) is missing required "height" property.

使用したファイルは以下の通りです。

PreviewImage.tsx
"use client";

import Image from "next/image";
import styled from "styled-component";
import { Skeleton } from "@mui/material";
import { FC, useEffect, useState } from "react";

type PreviewProps = {
  file: File | null;
};

const styledImage = styled(Image)`
    width: 80%;
`;

const PreviewImage: FC<PreviewProps> = ({ file }) => {
  const [url, setUrl] = useState<string>("");
  const isLoading = file && !url;

  useEffect(() => {
    if (!file) return;

    let reader: FileReader | null = new FileReader();
    reader.onloadend = () => {
      const res = reader!.result;
      if (res && typeof res === "string") {
        setUrl(res);
      }
    };
    reader.readAsDataURL(file);

    return () => {
      reader = null;
    };
  }, [file]);

  return file ? isLoading ? <Skeleton /> : <StyledImage src={url} alt={file.name} /> : null;
};

export default PreviewImage;

原因

next/imageのImageコンポーネントにはwidthheightの両方を指定する必要があるようです。
ただ、StyledImageheightを追加しても同様のエラーが起こったので、Imageそのものにwidthheightを指定する必要があると思われます。

修正後のファイル

previewImage.tsx
import Image from "next/image";
import { Skeleton } from "@mui/material";
import { FC, useEffect, useState } from "react";

type PreviewProps = {
  file: File | null;
};

const PreviewImage: FC<PreviewProps> = ({ file }) => {
  const [url, setUrl] = useState<string>("");
  const isLoading = file && !url;

  useEffect(() => {
    if (!file) return;

    let reader: FileReader | null = new FileReader();
    reader.onloadend = () => {
      const res = reader!.result;
      if (res && typeof res === "string") {
        setUrl(res);
      }
    };
    reader.readAsDataURL(file);

    return () => {
      reader = null;
    };
  }, [file]);

  return file ? isLoading ? <Skeleton /> : <Image src={url} alt={file.name} width={300} height={200} /> : null;
};

export default PreviewImage;
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?