Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 79 additions & 81 deletions src/content/reference/react-dom/components/img.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ title: "<img>"

<Intro>

The [built-in browser `<img>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) lets you embed an image.
[ブラウザ組み込みの `<img>` コンポーネント](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img)を使うことで、画像を埋め込むことができます。

```js
<img src="photo.jpg" alt="A person walking through a park" />
Expand All @@ -16,50 +16,50 @@ The [built-in browser `<img>` component](https://developer.mozilla.org/en-US/doc

---

## Reference {/*reference*/}
## リファレンス {/*reference*/}

### `<img>` {/*img*/}

To display an image, render the [built-in browser `<img>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img).
画像を表示するには、[ブラウザ組み込みの `<img>` コンポーネント](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img)をレンダーします。

```js
<img src="photo.jpg" alt="A person walking through a park" />
```

[See more examples below.](#usage)
[さらに例を見る](#usage)

#### Props {/*props*/}
#### props {/*props*/}

`<img>` supports all [common element props.](/reference/react-dom/components/common#common-props)
`<img>` は、[一般的な要素の props](/reference/react-dom/components/common#common-props) をすべてサポートしています。

* `alt`: a string. Specifies alternative text for the image. Use an empty string for a purely decorative image.
* `crossOrigin`: a string. Specifies the [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use when fetching the image. The possible values are `anonymous` and `use-credentials`.
* `decoding`: a string. Suggests whether the browser should wait to decode the image before presenting other content. The possible values are `async`, `sync`, and `auto` (the default).
* `fetchPriority`: a string. Suggests a relative priority for fetching the image. The possible values are `high`, `low`, and `auto` (the default). During server rendering, `fetchPriority="low"` also prevents React from [automatically preloading the image.](#controlling-image-preloading-during-server-rendering)
* `height`: a number or string. Specifies the rendered height of the image.
* `loading`: a string. Specifies whether the browser should defer loading the image until it is near the viewport. The possible values are `eager` (the default) and `lazy`. Setting `loading="lazy"` prevents React from [automatically preloading the image.](#controlling-image-preloading-during-server-rendering)
* `onError`: an [event handler](/reference/react-dom/components/common#event-handler) function. Fires when the image fails to load.
* `onLoad`: an [event handler](/reference/react-dom/components/common#event-handler) function. Fires when the image finishes loading. Passing `onLoad` prevents React from [waiting for the image during a client-rendered View Transition update.](#waiting-for-an-image-during-a-view-transition)
* `referrerPolicy`: a string. Specifies the [referrer information](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#referrerpolicy) to send when fetching the image.
* `sizes`: a string. Specifies the image sizes for different page layouts. Used with `srcSet`.
* `src`: a string. Specifies the URL of the image.
* `srcSet`: a string. Specifies one or more candidate image sources for the browser to choose from.
* `useMap`: a string. Associates the image with a [client-side image map](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map).
* `width`: a number or string. Specifies the rendered width of the image.
* `alt`: 文字列。画像の代替テキストを指定します。純粋に装飾目的の画像には空文字列を使用します。
* `crossOrigin`: 文字列。画像のフェッチ時に使用する [CORS ポリシー](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin)を指定します。可能な値は `anonymous` と `use-credentials` です。
* `decoding`: 文字列。他のコンテンツを表示する前に、ブラウザが画像のデコードを待つべきかどうかのヒントです。可能な値は `async`、`sync`、`auto`(デフォルト)です。
* `fetchPriority`: 文字列。画像のフェッチに対する相対的な優先度のヒントです。可能な値は `high`、`low`、`auto`(デフォルト)です。サーバレンダリング中は、`fetchPriority="low"` を指定すると、React による[画像の自動プリロード](#controlling-image-preloading-during-server-rendering)も行われなくなります。
* `height`: 数値または文字列。画像の表示時の高さを指定します。
* `loading`: 文字列。画像がビューポートの近くに来るまで、ブラウザが画像の読み込みを遅延させるかどうかを指定します。可能な値は `eager`(デフォルト)と `lazy` です。`loading="lazy"` を設定すると、React による[画像の自動プリロード](#controlling-image-preloading-during-server-rendering)が行われなくなります。
* `onError`: [イベントハンドラ](/reference/react-dom/components/common#event-handler)関数。画像の読み込みに失敗したときに発火します。
* `onLoad`: [イベントハンドラ](/reference/react-dom/components/common#event-handler)関数。画像の読み込みが完了したときに発火します。`onLoad` を渡すと、[クライアントでのレンダーによるビュー遷移 (View Transition) の更新中に、React が画像を待機する動作](#waiting-for-an-image-during-a-view-transition)が行われなくなります。
* `referrerPolicy`: 文字列。画像のフェッチ時に送信する[リファラ情報](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#referrerpolicy)を指定します。
* `sizes`: 文字列。ページレイアウトごとの画像サイズを指定します。`srcSet` と組み合わせて使用します。
* `src`: 文字列。画像の URL を指定します。
* `srcSet`: 文字列。ブラウザが選択できる画像ソースの候補を 1 つ以上指定します。
* `useMap`: 文字列。画像を[クライアントサイドイメージマップ](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map)と関連付けます。
* `width`: 数値または文字列。画像の表示時の幅を指定します。

#### Caveats {/*caveats*/}
#### 注意点 {/*caveats*/}

* Do not pass an empty string to `src`. It may cause the browser to request the current page again. React warns in development and omits the attribute. To render no image, omit the `<img>` or pass `null` to `src`.
* `<img>` cannot have children or use `dangerouslySetInnerHTML`. React throws an error if you pass either.
* `fetchPriority="low"` does not stop React from waiting for the image to load and decode during a client-rendered View Transition update. Use `loading="lazy"` or an `onLoad` handler to opt out of that behavior.
* `src` に空文字列を渡さないでください。ブラウザが現在のページを再度リクエストしてしまう可能性があります。React は開発環境では警告を表示し、この属性を省略します。画像を何も表示しない場合は、`<img>` 自体を省略するか、`src` に `null` を渡してください。
* `<img>` は子要素を持つことができず、`dangerouslySetInnerHTML` も使用できません。いずれかを渡すと React はエラーをスローします。
* `fetchPriority="low"` を指定しても、クライアントでのレンダーによるビュー遷移の更新中に React が画像の読み込みを待機する動作は止まりません。この動作をオプトアウトするには、`loading="lazy"` を指定するか `onLoad` ハンドラを渡してください。

---

## Usage {/*usage*/}
## 使用法 {/*usage*/}

### Displaying an image {/*displaying-an-image*/}
### 画像を表示する {/*displaying-an-image*/}

Pass the image URL to `src` and a text description to `alt`:
`src` に画像の URL を、`alt` にテキストによる説明を渡します。

<Sandpack>

Expand All @@ -85,15 +85,15 @@ img {

</Sandpack>

Specify `width` and `height` when you know the image dimensions so the browser can reserve space before the image loads. For a decorative image, pass `alt=""` so that screen readers ignore it.
画像のサイズが分かっている場合は `width` と `height` を指定してください。これにより、ブラウザが画像の読み込み前に表示領域を確保できるようになります。装飾目的の画像には `alt=""` を渡して、スクリーンリーダに無視されるようにしてください。

---

### Controlling image preloading during server rendering {/*controlling-image-preloading-during-server-rendering*/}
### サーバレンダリング中の画像のプリロードを制御する {/*controlling-image-preloading-during-server-rendering*/}

During server rendering, React automatically generates a preload hint for an `<img>` by default. This can let the browser start fetching the image before it encounters the `<img>` in the rendered HTML.
サーバレンダリング中、React はデフォルトで `<img>` に対するプリロードヒントを自動的に生成します。これにより、ブラウザはレンダーされた HTML 内で `<img>` に出会う前に、画像のフェッチを開始できるようになります。

Add `loading="lazy"` or `fetchPriority="low"` to an image that should not receive this hint:
このヒントを生成すべきでない画像には、`loading="lazy"` または `fetchPriority="low"` を追加します。

```js
function ProductPage() {
Expand All @@ -107,43 +107,44 @@ function ProductPage() {
}
```

In this example, React generates a preload hint only for `hero.jpg`. Depending on the server API or framework, React may render the equivalent of this element:
この例では、React は `hero.jpg` に対してのみプリロードヒントを生成します。使用するサーバ API やフレームワークによっては、React は以下のような要素に相当するものをレンダーすることがあります。

```html
<link rel="preload" as="image" href="hero.jpg" />
```

React may instead provide the same hint in a `Link` response header. The other two images keep their `loading` and `fetchPriority` props in the rendered HTML, but React does not generate preload hints for them. The `loading="lazy"` prop asks the browser to defer loading an image until it approaches the viewport. The `fetchPriority="low"` prop allows the image to load immediately, but tells the browser to fetch it at a lower priority.
代わりに、同じヒントを `Link` レスポンスヘッダで提供する場合もあります。残りの 2 つの画像については、レンダーされた HTML に `loading` や `fetchPriority` の props がそのまま残りますが、React はプリロードヒントを生成しません。`loading="lazy"` は、画像がビューポートに近づくまで読み込みを遅延させるようブラウザに求めます。`fetchPriority="low"` は画像をすぐに読み込むことを許可しますが、低い優先度でフェッチするようブラウザに伝えます。

React also does not automatically preload an image when it is inside a `<picture>` or `<noscript>` element, or when its `src` or `srcSet` is a data URL.
また、画像が `<picture>` 要素や `<noscript>` 要素の内部にある場合や、`src` または `srcSet` が data URL である場合も、React は画像を自動的にプリロードしません。

If you render an image through a framework or a component library, consult its documentation for the default behavior. React decides whether to generate an automatic preload from the props of the underlying `<img>`. For example, an image component may add `loading="lazy"` by default and provide a separate option for explicitly preloading selected images.
フレームワークやコンポーネントライブラリを通じて画像をレンダーしている場合は、デフォルトの動作についてそれぞれのドキュメントを参照してください。自動プリロードを生成するかどうかは、内部でレンダーされる `<img>` の props に基づいて React が決定します。例えば、画像コンポーネントによっては、デフォルトで `loading="lazy"` を付加し、選択した画像を明示的にプリロードするための別のオプションを提供している場合があります。

To create an explicit preload hint, call [`preload`](/reference/react-dom/preload).
プリロードヒントを明示的に作成するには、[`preload`](/reference/react-dom/preload) を呼び出します。

---

### Waiting for an image during a View Transition {/*waiting-for-an-image-during-a-view-transition*/}
### ビュー遷移中に画像の読み込みを待機する {/*waiting-for-an-image-during-a-view-transition*/}

During a client-rendered [`<ViewTransition>`](/reference/react/ViewTransition) update, React may wait for an image to load and decode before starting the animation. This applies when a new `<img>` with a non-empty `src` is rendered, or when an existing image's `src` or `srcSet` changes. The image must be inside the `<ViewTransition>` subtree and must not have `loading="lazy"` or an `onLoad` handler. React does not wait for images during synchronous updates.
[`<ViewTransition>`](/reference/react/ViewTransition) による更新中、React はアニメーションを開始する前に、表示される画像の読み込みを最大 500 ミリ秒待機します。この対象には、新たにレンダーされた `<img>` 要素と、`src` や `srcSet` が変更された既存の画像が含まれます。`loading="lazy"` を設定するか `onLoad` ハンドラを追加すると、その画像は対象外になります。

When a Suspense boundary reveals streamed content inside a `<ViewTransition>`, React may also wait for visible images with a non-empty `src` that do not have `loading="lazy"`. React stops waiting after a timeout so that a slow image does not block the update indefinitely.

In this example, the Suspense boundary is wrapped in a `<ViewTransition>` and shows a profile skeleton until the portrait has loaded.

For comparison, the second button inserts the same card directly into the DOM. The card appears immediately, and the browser displays the image after it loads:
サスペンスバウンダリが中身を表示する際に、`<ViewTransition>` の内側と外側とで同じ画像の表示のされ方がどう異なるか、比較してみましょう。

<Sandpack>

```js
import { ViewTransition, Suspense, useState, startTransition } from 'react';
import { freshImageUrl } from './image.js';
import VanillaProfile from './VanillaProfile.js';

function Profile({ src }) {
import {
ViewTransition,
Suspense,
use,
useState,
} from 'react';
import { fetchImageSrc } from './image.js';

function Profile({ cacheKey }) {
const src = use(fetchImageSrc(cacheKey));
return (
<div className="card">
<img src={src} alt="Jack Pope" width={80} height={80} />
<img src={src} alt="" width={80} height={80} />
<p>Jack Pope</p>
</div>
);
Expand All @@ -159,56 +160,51 @@ function ProfilePlaceholder() {
}

export default function App() {
const [src, setSrc] = useState(null);
const [showWithTransition, setShowWithTransition] =
useState(false);
const [showWithoutTransition, setShowWithoutTransition] =
useState(false);
return (
<>
<button
onClick={() => {
startTransition(() => {
setSrc(freshImageUrl());
});
}}>
Show profile
<button onClick={() => setShowWithTransition(true)}>
Show profile with View Transition
</button>
{src && (
{showWithTransition && (
<ViewTransition>
<Suspense fallback={<ProfilePlaceholder />}>
<Profile src={src} />
<Profile cacheKey="with-transition" />
</Suspense>
</ViewTransition>
)}
<hr />
<VanillaProfile />
<button onClick={() => setShowWithoutTransition(true)}>
Show profile without View Transition
</button>
{showWithoutTransition && (
<Suspense fallback={<ProfilePlaceholder />}>
<Profile cacheKey="without-transition" />
</Suspense>
)}
</>
);
}
```

```js src/VanillaProfile.js
import { useRef } from 'react';
import { freshImageUrl } from './image.js';
```js src/image.js hidden
// Normally, the caching logic would be inside a framework.
const cache = new Map();

export default function VanillaProfile() {
const ref = useRef(null);
function show() {
ref.current.innerHTML = `<div class="card">
<img src="${freshImageUrl()}" alt="Jack Pope" width="80" height="80" />
<p>Jack Pope</p>
</div>`;
export function fetchImageSrc(cacheKey) {
if (!cache.has(cacheKey)) {
cache.set(cacheKey, loadImageSrc());
}
return (
<>
<button onClick={show}>Show profile (direct DOM update)</button>
<div ref={ref} />
</>
);
return cache.get(cacheKey);
}
```

```js src/image.js hidden
// Add a unique parameter so the image isn't cached,
// and every run shows the loading state.
export function freshImageUrl() {
async function loadImageSrc() {
// Delay the response so the Suspense fallback is visible.
await new Promise(resolve => setTimeout(resolve, 1000));
// Add a unique parameter so the image isn't cached.
return 'https://react.dev/images/team/jack-pope.jpg?t=' + Date.now();
}
```
Expand Down Expand Up @@ -255,3 +251,5 @@ hr {
```

</Sandpack>

`<ViewTransition>` がある場合、React は画像の読み込み中、最大 500 ミリ秒間スケルトンを表示し続けるため、画像が揃った状態でカードを表示できます。`<ViewTransition>` がない場合、サスペンスはプロミスが解決した時点でスケルトンの表示をやめます。画像がまだ読み込み中であれば、先にカードが表示され、画像は後から表示されます。
Loading