LoginSignup
1

More than 1 year has passed since last update.

posted at

Next.js での画像の取扱について(背景に画像を設定する方法や外部 URL から画像を引用する方法にも触れています)

初めに~~~~

自分の学習メモです
随分と時間がかかったので同じ内容で検索している方ように載せておきます
他でもこの文章は使い回しするかもしれません
間違えなどあればご指摘いただけると幸いです

img タグではなく Image タグを使う

Next.js には next/image というツールがあり

これを使うことで画像を自動でリサイズしてくれる

画像自体のサイズが大幅に下がるのでレンダリングも早くなる

事前準備

import Image from 'next/image';

Image タグを使うページで宣言する

public フォルダから画像を引用する

public フォルダに sample.jpeg というファイルを置き参照する

尚、public フォルダを参照するのは next.js がStatic File Servingという機能を持っているからである

next.js では public フォルダ下にあるデータは'/'で参照できるようになるということ

参考サイト

日本語版

// index.js
<Image
  src="/sample.jpeg"
  layout="fill"
  // width={500}
  // height={500}
/>
  • src 属性(プロパティ)は必須
  • layout 属性は width と height 属性でも可能(どちらか片方は必須)

外部 URL から画像引用する場合

next.config.js を設定し、関数で呼ぶ必要がある

// next.config.js
module.exports = {
  images: {
    domains: ['example.com'],
  },
};

と、設定する

外部 URL 画像はこちらのフリー素材から借りた

今回は

https://jungle-time.com/wp-content/uploads/2018/03/red-fox-2230730_1280.jpg

という URL 画像を参照して解説する

// index.js
const foxImage = () => {
  return `https://jungle-time.com/wp-content/uploads/2018/03/red-fox-2230730_1280.jpg`;
};

と、画像を引っぱてきて

// index.js
<Image
  loader={foxImage}
  src="fox"
  layout="fill"
  // objectFit="cover"
  // width={500}
  // height={500}
/>

とすると反映される

なお、

  • loader 属性(プロパティ)は必須
  • src 属性は必須
  • layout 属性の代わりに width と height 属性でも可能
  • object-fit 属性は任意

object-fit とは?

背景画像を設定する場合

上記で既に示しているが

// index.js
<Image
  loader={foxImage}
  src="fox"
  layout="fill"
  objectFit="cover"
  //
/>

または

<Image
  src="/sample.jpeg"
  layout="fill"
  objectFit="cover"
  //
/>

外部 URL で引いてくる場合でも public フォルダ参照でも

上記のようにすると背景になる

参考サイト
https://nextjs.org/docs/api-reference/next/image
https://www.forcia.com/blog/001561.html
https://dev.to/dolearning/importing-svgs-to-next-js-nna
https://medium.com/eincode/how-to-use-next-js-image-component-dfbf3725b12
https://nextjs.org/docs/api-reference/next/image

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
What you can do with signing up
1