1
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?

Next.jsのImageコンポーネント入門 — imgタグより何が嬉しいのか

1
Posted at

Next.jsのImageコンポーネント入門 — imgタグより何が嬉しいのか

はじめに

Next.jsには通常のHTMLの<img>タグの代わりに使う<Image>コンポーネントがあります。

「なぜわざわざ専用のコンポーネントを使うの?」という疑問に答えます。


imgタグとImageコンポーネントの違い

<img> <Image>(Next.js)
画像の最適化 なし 自動でWebP変換・リサイズ
遅延読み込み 手動設定が必要 デフォルトでON
サイズ指定 必須ではない 必須(CLS防止のため)
外部画像 そのまま使える next.config.jsでドメイン許可が必要

基本の使い方

import Image from 'next/image';

export default function Profile() {
  return (
    <Image
      src="/images/profile.jpg"  // publicフォルダからのパス
      alt="プロフィール画像"
      width={200}
      height={200}
    />
  );
}

widthheight必須です。指定することでレイアウトのずれ(CLS)を防げます。


外部URLの画像を使う場合

外部のURLをsrcに指定するには、next.config.jsにドメインを許可する設定が必要です。

// next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'example.com',
      },
    ],
  },
};
<Image
  src="https://example.com/photo.jpg"
  alt="外部画像"
  width={400}
  height={300}
/>

親要素いっぱいに広げる(fill)

コンテナに合わせて画像を広げたいときはfillを使います。

<div style={{ position: 'relative', width: '100%', height: '300px' }}>
  <Image
    src="/images/banner.jpg"
    alt="バナー"
    fill
    style={{ objectFit: 'cover' }}
  />
</div>

fillを使うときは親要素にposition: relativeが必要です。


priorityで優先読み込み

ファーストビューに表示される画像(ヒーロー画像など)はpriorityを指定すると最初に読み込まれます。

<Image
  src="/images/hero.jpg"
  alt="ヒーロー画像"
  width={1200}
  height={600}
  priority
/>

priorityをつけると遅延読み込みがOFFになり、優先的に取得されます。


まとめ

やること 書き方
ローカル画像 src="/images/xxx.jpg" + width + height
外部画像 next.config.jsでドメイン許可 + src="https://..."
全体に広げる fill + 親にposition: relative
優先読み込み priority属性

JavaのSpring MVCでは画像リソースの最適化は別途設定が必要でしたが、Next.jsでは<Image>コンポーネントを使うだけで自動化されます。

1
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
1
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?