LoginSignup
0
0

コンポーネントにnext/imageを使いたいけどエラーで表示されない!?

Posted at

下記のようなコンポーネントを作成しました。
ただ、コンポーネントが表示されないエラーが発生しました。

この記事ではnext/imageでサンプル画像を使いたいと思いエラーになった時にお役立ていただけると思います!

何が起こったのか? Unhandled Runtime Error

今回作成したコンポーネントは下記となります。

'use client';
import { FC, PropsWithChildren } from 'react';
import Image from 'next/image';

type Props = PropsWithChildren<{
  title: string;
  bgColor?: string;
  advanced?: boolean;
}>;

export const Card: FC<Props> = ({ title, children, bgColor }) => {
  return (
    <div className={`w-72 rounded p-2 border border-defaultBorder ${bgColor}`}>
      <div className="w-full h-auto mb-3">
        <Image
          src="https://placehold.jp/640x360.png"
          alt=""
          width={640}
          height={360}
        />
      </div>
      <div className="w-full h-auto bg-white box-border">
        <p className="text-lg font-bold mb-1">{title}</p>
        <p className="text-sm">{children}</p>
      </div>
    </div>
  );
};

上記の状態だとエラーになり、コンポーネントがレンダリングされません…
エラー内容は下記の通りです。

Unhandled Runtime Error
Error: Invalid src prop (https://placehold.jp/640x360.png) on `next/image`, hostname "placehold.jp" is not configured under images in your `next.config.js`
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host

なぜか上記のエラーが画面に表示されず、ただ真っ白な画面(コンポーネントが表示されない)が表示されるのみでエラーの原因がわからない状態になってしまい解決に時間がかかりました…。

解決策

解決方法はホストの定義をnext.config.jsで行います。
公式サイトにも記述があるので参考にしてください!

今回はhttps://placehold.jp/から画像を呼び出したかったので下記のように記述するとコンポーネントが表示されるようになりました!

const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'placehold.jp',
        port: '',
        pathname: '/640x360.png',
      },
    ],
  },
};

まとめ

画像にサンプル画像を使おうとアップロードせずに使おうと考えましたが、不用意に時間を消費してしまいました…。
未定義ホストへのアクセスは許可してあげないといけないことを覚えておきたいと思います…。

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