diff --git a/src/content/learn/conditional-rendering.md b/src/content/learn/conditional-rendering.md index cbae68cec..5029f60fb 100644 --- a/src/content/learn/conditional-rendering.md +++ b/src/content/learn/conditional-rendering.md @@ -1,24 +1,24 @@ --- -title: Conditional Rendering +title: 条件付きレンダー --- -Your components will often need to display different things depending on different conditions. In React, you can conditionally render JSX using JavaScript syntax like `if` statements, `&&`, and `? :` operators. +様々な条件によって、コンポーネントに表示させる内容を変化させたいことがあります。React では、JavaScript の `if` 文や `&&`、`? :` 演算子などの構文を使うことで、JSX を条件付きでレンダーできます。 -* How to return different JSX depending on a condition -* How to conditionally include or exclude a piece of JSX -* Common conditional syntax shortcuts you’ll encounter in React codebases +* 条件に応じて異なる JSX を返す方法 +* JSX の一部を条件によって表示したり除外したりする方法 +* React コードベースでよく使われる条件式のショートカット記法 -## Conditionally returning JSX {/*conditionally-returning-jsx*/} +## 条件を満たす場合に JSX を返す {/*conditionally-returning-jsx*/} -Let’s say you have a `PackingList` component rendering several `Item`s, which can be marked as packed or not: +例えば、複数の `Item` をレンダーする `PackingList` コンポーネントがあり、各 `Item` に梱包が終わっているかどうか表示させたいとしましょう。 @@ -52,9 +52,9 @@ export default function PackingList() { -Notice that some of the `Item` components have their `isPacked` prop set to `true` instead of `false`. You want to add a checkmark (✔) to packed items if `isPacked={true}`. +複数の `Item` コンポーネントのうち一部のみで `isPacked` プロパティが `false` ではなく `true` になっていることに注意してください。目的は、`isPacked={true}` の場合にのみチェックマーク (✔) を表示させることです。 -You can write this as an [`if`/`else` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) like so: +これは [`if`/`else` 文](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)を使って、以下のように書くことができます。 ```js if (isPacked) { @@ -63,7 +63,7 @@ if (isPacked) { return
  • {name}
  • ; ``` -If the `isPacked` prop is `true`, this code **returns a different JSX tree.** With this change, some of the items get a checkmark at the end: +`isPacked` プロパティが `true` だった場合、このコードは**異なる JSX ツリーを返します**。この変更により、一部のアイテムの末尾にチェックマークが表示されます。 @@ -100,13 +100,13 @@ export default function PackingList() { -Try editing what gets returned in either case, and see how the result changes! +それぞれの場合に返される内容を編集してみて、表示がどのように変化するか確認しましょう。 -Notice how you're creating branching logic with JavaScript's `if` and `return` statements. In React, control flow (like conditions) is handled by JavaScript. +条件分岐ロジックを実装するために JavaScript の `if` や `return` 文を使ったことに着目してください。React では、制御フロー(条件分岐など)は JavaScript で処理されます。 -### Conditionally returning nothing with `null` {/*conditionally-returning-nothing-with-null*/} +### `null` を使って何も返さないようにする {/*conditionally-returning-nothing-with-null*/} -In some situations, you won't want to render anything at all. For example, say you don't want to show packed items at all. A component must return something. In this case, you can return `null`: +場合によっては、何もレンダーしたくないことがあります。例えば、梱包済みの荷物は一切表示したくない、という場合です。コンポーネントは常に何かを返す必要があります。このような場合、`null` を返すことができます。 ```js if (isPacked) { @@ -115,7 +115,7 @@ if (isPacked) { return
  • {name}
  • ; ``` -If `isPacked` is true, the component will return nothing, `null`. Otherwise, it will return JSX to render. +`isPacked` が `true` の場合、コンポーネントは「何も表示しない」という意味で `null` を返します。それ以外の場合、レンダーする JSX を返します。 @@ -152,23 +152,23 @@ export default function PackingList() { -In practice, returning `null` from a component isn't common because it might surprise a developer trying to render it. More often, you would conditionally include or exclude the component in the parent component's JSX. Here's how to do that! +実際には、レンダーしようとしている開発者を混乱させる可能性があるため、コンポーネントから `null` を返すことは一般的ではありません。代わりに、親コンポーネント側の JSX で条件付きでコンポーネントを含めたり除外したりすることが多いでしょう。以下はその方法です。 -## Conditionally including JSX {/*conditionally-including-jsx*/} +## 条件付きで JSX を含める {/*conditionally-including-jsx*/} -In the previous example, you controlled which (if any!) JSX tree would be returned by the component. You may already have noticed some duplication in the render output: +前の例では、コンポーネントが複数の JSX ツリーのうちどれを返すのか(あるいは何も返さないのか)をコントロールしていました。しかし、レンダー出力に重複があることに気付かれたでしょう。 ```js
  • {name} ✔
  • ``` -is very similar to +これは以下とほとんど同じです。 ```js
  • {name}
  • ``` -Both of the conditional branches return `
  • ...
  • `: +どちらの分岐も `
  • ...
  • ` を返しています。 ```js if (isPacked) { @@ -177,13 +177,13 @@ if (isPacked) { return
  • {name}
  • ; ``` -While this duplication isn't harmful, it could make your code harder to maintain. What if you want to change the `className`? You'd have to do it in two places in your code! In such a situation, you could conditionally include a little JSX to make your code more [DRY.](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) +この重複に実害はありませんが、コードの保守性は悪化してしまいます。たとえば `className` を変更したくなったら? コード内の 2 か所で変更が必要になってしまいますよね。このような状況では、条件付きで小さな JSX を含めることで、コードをより [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) に保つことができます。 -### Conditional (ternary) operator (`? :`) {/*conditional-ternary-operator--*/} +### 条件 (三項) 演算子 (`? :`) {/*conditional-ternary-operator--*/} -JavaScript has a compact syntax for writing a conditional expression -- the [conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) or "ternary operator". +JavaScript には、条件式を書くためのコンパクトな構文があります。それが[条件演算子](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)または「三項 (ternary) 演算子」と呼ばれるものです。 -Instead of this: +以下のコードは: ```js if (isPacked) { @@ -192,7 +192,7 @@ if (isPacked) { return
  • {name}
  • ; ``` -You can write this: +代わりに以下のように書くことができます: ```js return ( @@ -202,17 +202,17 @@ return ( ); ``` -You can read it as *"if `isPacked` is true, then (`?`) render `name + ' ✔'`, otherwise (`:`) render `name`"*. +これは「*`isPacked` が true なら `name + ' ✔'` をレンダーし、それ以外 (`:`) の場合は `name` をレンダーする*」というように読んでください。 -#### Are these two examples fully equivalent? {/*are-these-two-examples-fully-equivalent*/} +#### この 2 つの例は完全に同等か? {/*are-these-two-examples-fully-equivalent*/} -If you're coming from an object-oriented programming background, you might assume that the two examples above are subtly different because one of them may create two different "instances" of `
  • `. But JSX elements aren't "instances" because they don't hold any internal state and aren't real DOM nodes. They're lightweight descriptions, like blueprints. So these two examples, in fact, *are* completely equivalent. [Preserving and Resetting State](/learn/preserving-and-resetting-state) goes into detail about how this works. +オブジェクト指向プログラミングのバックグラウンドをお持ちの場合、2 つの例の一方では `
  • ` の「インスタンス」が 2 つ作られるため、これらがわずかに異なると考えてしまうかもしれません。しかし JSX 要素は内部に状態を持たず、実際の DOM 要素でもないため、「インスタンス」ではありません。JSX は軽量な「説明書き」であり設計図のようなものです。従って上記の 2 つの例は実際に完全に同等です。[Preserving and Resetting State](/learn/preserving-and-resetting-state) を参照してください。 -Now let's say you want to wrap the completed item's text into another HTML tag, like `` to strike it out. You can add even more newlines and parentheses so that it's easier to nest more JSX in each of the cases: +次に、梱包済みのアイテムを、取り消し線を表示する `` のような別のタグで囲みたいとしましょう。このような場合、true と false のそれぞれの場合に対応する改行や括弧を追加することで、ネストされた JSX を読みやすくすることができます。 @@ -256,11 +256,11 @@ export default function PackingList() { -This style works well for simple conditions, but use it in moderation. If your components get messy with too much nested conditional markup, consider extracting child components to clean things up. In React, markup is a part of your code, so you can use tools like variables and functions to tidy up complex expressions. +これはシンプルな条件分岐の場合にはうまく動きますが、使いすぎないようにしましょう。条件のためのマークアップが増えすぎてコンポーネントが見づらくなった場合は、見やすくするために子コンポーネントを抽出することを検討してください。React ではマークアップはプログラミングコードの一種ですので、変数や関数といった道具を利用して複雑な式を読みやすく整頓することができます。 -### Logical AND operator (`&&`) {/*logical-and-operator-*/} +### 論理 AND 演算子 (`&&`) {/*logical-and-operator-*/} -Another common shortcut you'll encounter is the [JavaScript logical AND (`&&`) operator.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#:~:text=The%20logical%20AND%20(%20%26%26%20)%20operator,it%20returns%20a%20Boolean%20value.) Inside React components, it often comes up when you want to render some JSX when the condition is true, **or render nothing otherwise.** With `&&`, you could conditionally render the checkmark only if `isPacked` is `true`: +もうひとつよく使われるショートカットは、[JavaScript の論理 AND (`&&`) 演算子](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#:~:text=The%20logical%20AND%20(%20%26%26%20)%20operator,it%20returns%20a%20Boolean%20value.)です。React コンポーネント内で、条件が真の場合に JSX をレンダーし、**それ以外の場合は何もレンダーしない**という場合にしばしば使用されます。`&&` を使用すると、`isPacked` が `true` の場合にのみチェックマークを条件付きでレンダーできます。 ```js return ( @@ -270,9 +270,9 @@ return ( ); ``` -You can read this as *"if `isPacked`, then (`&&`) render the checkmark, otherwise, render nothing"*. +これは「*`isPacked` なら (`&&`)、チェックマークをレンダーし、それ以外の場合には何もレンダーしない*」のように読んでください。 -Here it is in action: +以下が完全に動作する例です: @@ -310,30 +310,30 @@ export default function PackingList() { -A [JavaScript && expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND) returns the value of its right side (in our case, the checkmark) if the left side (our condition) is `true`. But if the condition is `false`, the whole expression becomes `false`. React considers `false` as a "hole" in the JSX tree, just like `null` or `undefined`, and doesn't render anything in its place. +[JavaScript の && 式](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND) は、左側(条件)が `true` である場合、右側(今回の場合はチェックマーク)の値を返します。しかし、条件が `false` である場合、式全体が `false` になります。Reactは、`false` を JSX ツリーの「穴」と見なし、`null` や `undefined` と同様に、何もレンダーしません。 -**Don't put numbers on the left side of `&&`.** +**`&&` の左辺に数値を置かない** -To test the condition, JavaScript converts the left side to a boolean automatically. However, if the left side is `0`, then the whole expression gets that value (`0`), and React will happily render `0` rather than nothing. +JavaScript は条件をテストする際、左の辺を自動的に真偽値に変換します。しかし、左の辺が `0` の場合は、式全体がその `0` という値に評価されてしまうため、React は何もレンダーしないのではなく `0` を表示します。 -For example, a common mistake is to write code like `messageCount &&

    New messages

    `. It's easy to assume that it renders nothing when `messageCount` is `0`, but it really renders the `0` itself! +たとえば、よくある間違いとして `messageCount &&

    New messages

    ` のようにコードを書くことが挙げられます。`messageCount` が `0` の場合は何も表示しないと思われがちですが、実際には `0` そのものが表示されてしまいます! -To fix it, make the left side a boolean: `messageCount > 0 &&

    New messages

    `. +これを修正するには、左の値を真偽値にしてください: `messageCount > 0 &&

    New messages

    `。
    -### Conditionally assigning JSX to a variable {/*conditionally-assigning-jsx-to-a-variable*/} +### 条件付きで JSX を変数に割り当てる {/*conditionally-assigning-jsx-to-a-variable*/} -When the shortcuts get in the way of writing plain code, try using an `if` statement and a variable. You can reassign variables defined with [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), so start by providing the default content you want to display, the name: +上記のようなショートカットを使って簡潔にコードを記述するのが難しいと感じた場合は、`if` 文と変数を使用してみてください。[`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) で定義した変数は再代入も可能ですので、最初に表示したいデフォルトの値 (name) を指定します。 ```js let itemContent = name; ``` -Use an `if` statement to reassign a JSX expression to `itemContent` if `isPacked` is `true`: +そして `if` 文を使って、`isPacked` が `true` の場合のみ `itemContent` に JSX 式を再割り当てします。 ```js if (isPacked) { @@ -341,7 +341,7 @@ if (isPacked) { } ``` -[Curly braces open the "window into JavaScript".](/learn/javascript-in-jsx-with-curly-braces#using-curly-braces-a-window-into-the-javascript-world) Embed the variable with curly braces in the returned JSX tree, nesting the previously calculated expression inside of JSX: +[波括弧は「JavaScript への窓口」](/learn/javascript-in-jsx-with-curly-braces#using-curly-braces-a-window-into-the-javascript-world)です。波括弧を使って JSX ツリーに変数を埋め込むことで、さきほど計算した値を JSX 内にネストすることができます。 ```js
  • @@ -349,7 +349,7 @@ if (isPacked) {
  • ``` -This style is the most verbose, but it's also the most flexible. Here it is in action: +このスタイルは最も長くなりますが、同時に最も柔軟です。以下が全体像です。 @@ -391,7 +391,7 @@ export default function PackingList() { -Like before, this works not only for text, but for arbitrary JSX too: +前述の通り、これはテキストのみでなく任意の JSX に対して使えます。 @@ -437,16 +437,16 @@ export default function PackingList() { -If you're not familiar with JavaScript, this variety of styles might seem overwhelming at first. However, learning them will help you read and write any JavaScript code -- and not just React components! Pick the one you prefer for a start, and then consult this reference again if you forget how the other ones work. +JavaScript に慣れていない場合、これだけ多様なスタイルがあると最初は圧倒されるかもしれません。しかし、これらを学ぶことは、React コンポーネントだけでなく、あらゆる JavaScript コードを読み書きできるようになるのにも役立ちます。最初は好みのスタイルを選んでスタートし、他のスタイルの仕組みを忘れた場合は、再度このリファレンスを参照してください。 -* In React, you control branching logic with JavaScript. -* You can return a JSX expression conditionally with an `if` statement. -* You can conditionally save some JSX to a variable and then include it inside other JSX by using the curly braces. -* In JSX, `{cond ? : }` means *"if `cond`, render ``, otherwise ``"*. -* In JSX, `{cond && }` means *"if `cond`, render ``, otherwise nothing"*. -* The shortcuts are common, but you don't have to use them if you prefer plain `if`. +* Reactでは、JavaScriptを使用して分岐ロジックを制御する。 +* `if` 文を使用して、条件に応じて JSX 式を返すことができる。 +* JSX 内で中身を条件付きで変数に保存し、波括弧を使用して他の JSX 内に含めることができる。 +* JSX 内の `{cond ? : }` は、「`cond`であれば``をレンダーし、そうでなければ `` をレンダーする」という意味である。 +* JSX 内の `{cond && }` は、「`cond` であれば `` をレンダーし、そうでなければ何もレンダーしない」という意味である。 +* これらのショートカットは一般的だが、プレーンな `if` が好きなら必ずしも使わなくて良い。 @@ -454,9 +454,9 @@ If you're not familiar with JavaScript, this variety of styles might seem overwh -#### Show an icon for incomplete items with `? :` {/*show-an-icon-for-incomplete-items-with--*/} +#### `? :` を使って未梱包アイコンを表示 {/*show-an-icon-for-incomplete-items-with--*/} -Use the conditional operator (`cond ? a : b`) to render a ❌ if `isPacked` isn’t `true`. +条件演算子 (`cond ? a : b`) を使って、`isPacked` が `true` でない場合は ❌ をレンダーするようにしてください。 @@ -534,15 +534,15 @@ export default function PackingList() { -#### Show the item importance with `&&` {/*show-the-item-importance-with-*/} +#### `&&` 演算子を使ったアイテムの重要度の表示 {/*show-the-item-importance-with*/} -In this example, each `Item` receives a numerical `importance` prop. Use the `&&` operator to render "_(Importance: X)_" in italics, but only for items that have non-zero importance. Your item list should end up looking like this: +この例では、それぞれの `Item` が数値型の `importance` プロパティを受け取ります。重要度が 0 以外の場合に限り、`&&` 演算子を使用して、斜体で "_(Importance: X)_" と表示するようにしてください。以下のような結果になるようにしましょう。 * Space suit _(Importance: 9)_ * Helmet with a golden leaf * Photo of Tam _(Importance: 6)_ -Don't forget to add a space between the two labels! +重要度を表示する場合は 2 つのテキストの間にスペースを入れることを忘れないでください! @@ -582,7 +582,7 @@ export default function PackingList() { -This should do the trick: +以下のようにすれば動きます: @@ -624,15 +624,15 @@ export default function PackingList() { -Note that you must write `importance > 0 && ...` rather than `importance && ...` so that if the `importance` is `0`, `0` isn't rendered as the result! +`importance` が `0` の場合に `0` が結果として表示されてしまわないよう、`importance && ...` ではなく `importance > 0 && ...` と書く必要があることに注意してください。 -In this solution, two separate conditions are used to insert a space between then name and the importance label. Alternatively, you could use a fragment with a leading space: `importance > 0 && <> ...` or add a space immediately inside the ``: `importance > 0 && ...`. +この答えでは、名前と重要度ラベルの間にスペースを挿入するために、2 つの条件が使用されています。代わりに、先頭にスペースを入れたフラグメントを使用することができます: `importance > 0 && <> ...` あるいは、`` の直接内側にスペースを追加することもできます: `importance > 0 && ...`。 -#### Refactor a series of `? :` to `if` and variables {/*refactor-a-series-of---to-if-and-variables*/} +#### 連続する `? :` を `if` と変数にリファクタ {/*refactor-a-series-of---to-if-and-variables*/} -This `Drink` component uses a series of `? :` conditions to show different information depending on whether the `name` prop is `"tea"` or `"coffee"`. The problem is that the information about each drink is spread across multiple conditions. Refactor this code to use a single `if` statement instead of three `? :` conditions. +この `Drink` コンポーネントは、`name` プロパティの値が `"tea"` か `"coffee"` かによって表示する情報を変えるために、`? :` を何度も使用しています。問題は、各ドリンクの情報が複数の条件分岐に分散してしまっていることです。このコードを、3 つの `? :` ではなく、単一の `if` 文を使うようにリファクタリングしてください。 @@ -665,11 +665,11 @@ export default function DrinkList() { -Once you've refactored the code to use `if`, do you have further ideas on how to simplify it? +コードを `if` 文を使用するようにリファクタリングしたら、さらに簡素化するアイデアはありますか? -There are multiple ways you could go about this, but here is one starting point: +複数のアプローチがありますが、ここでは1つの出発点として以下を示します: @@ -712,9 +712,9 @@ export default function DrinkList() { -Here the information about each drink is grouped together instead of being spread across multiple conditions. This makes it easier to add more drinks in the future. +これで、各ドリンクの情報が複数の条件分岐に分散されずにグループ化されてました。将来新しいドリンクを追加する際にも簡単になります。 -Another solution would be to remove the condition altogether by moving the information into objects: +別の解決策として、情報をオブジェクトに移動することで、条件を完全に削除することも可能です: diff --git a/src/content/learn/describing-the-ui.md b/src/content/learn/describing-the-ui.md index 6df4c0475..e23315657 100644 --- a/src/content/learn/describing-the-ui.md +++ b/src/content/learn/describing-the-ui.md @@ -1,29 +1,29 @@ --- -title: Describing the UI +title: UI の記述 --- -React is a JavaScript library for rendering user interfaces (UI). UI is built from small units like buttons, text, and images. React lets you combine them into reusable, nestable *components.* From web sites to phone apps, everything on the screen can be broken down into components. In this chapter, you'll learn to create, customize, and conditionally display React components. +React は、ユーザインターフェース(UI)を表示するための JavaScript ライブラリです。UI はボタンやテキスト、画像といった小さな要素から構成されています。React ではこれらを、ネストして再利用できる*コンポーネント*にまとめることができます。ウェブサイトであれ携帯電話アプリであれ、画面上のすべてのものはコンポーネントに分解することができます。この章では、React コンポーネントを作成し、カスタマイズし、条件付きで表示する方法について学びます。 -* [How to write your first React component](/learn/your-first-component) -* [When and how to create multi-component files](/learn/importing-and-exporting-components) -* [How to add markup to JavaScript with JSX](/learn/writing-markup-with-jsx) -* [How to use curly braces with JSX to access JavaScript functionality from your components](/learn/javascript-in-jsx-with-curly-braces) -* [How to configure components with props](/learn/passing-props-to-a-component) -* [How to conditionally render components](/learn/conditional-rendering) -* [How to render multiple components at a time](/learn/rendering-lists) -* [How to avoid confusing bugs by keeping components pure](/learn/keeping-components-pure) +* [初めてのコンポーネントの書き方](/learn/your-first-component) +* [コンポーネントファイルを複数に分ける理由とその方法](/learn/importing-and-exporting-components) +* [JSX を使って JavaScript にマークアップを追加する方法](/learn/writing-markup-with-jsx) +* [JSX 内で波括弧を使って JavaScript の機能にアクセスする方法](/learn/javascript-in-jsx-with-curly-braces) +* [コンポーネントを props を使ってカスタマイズする方法](/learn/passing-props-to-a-component) +* [コンポーネントを条件付きでレンダーする方法](/learn/conditional-rendering) +* [複数のコンポーネントを同時にレンダーする方法](/learn/rendering-lists) +* [コンポーネントを純粋に保つことで混乱を避ける方法](/learn/keeping-components-pure) -## Your first component {/*your-first-component*/} +## 初めてのコンポーネント {/*your-first-component*/} -React applications are built from isolated pieces of UI called *components*. A React component is a JavaScript function that you can sprinkle with markup. Components can be as small as a button, or as large as an entire page. Here is a `Gallery` component rendering three `Profile` components: +React アプリケーションは*コンポーネント*と呼ばれる独立した UI のパーツで構成されています。React コンポーネントとは、マークアップを添えることができる JavaScript 関数です。コンポーネントは、ボタンのような小さなものであることもあれば、ページ全体といった大きなものであることもあります。以下は、3 つの `Profile` コンポーネントをレンダーする `Gallery` コンポーネントの例です: @@ -57,13 +57,13 @@ img { margin: 0 10px 10px 0; height: 90px; } -Read **[Your First Component](/learn/your-first-component)** to learn how to declare and use React components. +**[初めてのコンポーネント](/learn/your-first-component)** を読んで、React コンポーネントの宣言方法、使用方法について学びましょう。 -## Importing and exporting components {/*importing-and-exporting-components*/} +## コンポーネントのインポートとエクスポート {/*importing-and-exporting-components*/} -You can declare many components in one file, but large files can get difficult to navigate. To solve this, you can *export* a component into its own file, and then *import* that component from another file: +1 つのファイルに多くのコンポーネントを宣言することもできますが、大きなファイルは取り回しが難しくなります。これを解決するために、コンポーネントを個別のファイルに*エクスポート*し、別のファイルからそのコンポーネントを*インポート*することができます: @@ -112,15 +112,15 @@ img { margin: 0 10px 10px 0; } -Read **[Importing and Exporting Components](/learn/importing-and-exporting-components)** to learn how to split components into their own files. +**[コンポーネントのインポートとエクスポート](/learn/importing-and-exporting-components)** を読んで、コンポーネントを個々の専用ファイルに分割する方法を学びましょう。 -## Writing markup with JSX {/*writing-markup-with-jsx*/} +## JSX でマークアップを記述する {/*writing-markup-with-jsx*/} -Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information. +各 React コンポーネントは、ブラウザにレンダーされるマークアップを含んだ JavaScript 関数です。React コンポーネントは、マークアップを表現するために JSX という拡張構文を使用します。JSX は HTML によく似ていますが、少し構文が厳密であり、動的な情報を表示することができます。 -If we paste existing HTML markup into a React component, it won't always work: +既存の HTML マークアップを React コンポーネントに貼り付けても、常にうまく機能するわけではありません。 @@ -149,7 +149,7 @@ img { height: 90px; } -If you have existing HTML like this, you can fix it using a [converter](https://transform.tools/html-to-jsx): +このような既存の HTML がある場合は、[コンバータ](https://transform.tools/html-to-jsx)を使って修正することができます。 @@ -181,13 +181,13 @@ img { height: 90px; } -Read **[Writing Markup with JSX](/learn/writing-markup-with-jsx)** to learn how to write valid JSX. +**[JSX でマークアップを記述する](/learn/writing-markup-with-jsx)** を読んで、正しい JSX の書き方を学びましょう。 -## JavaScript in JSX with curly braces {/*javascript-in-jsx-with-curly-braces*/} +## JSX に波括弧で JavaScript を含める {/*javascript-in-jsx-with-curly-braces*/} -JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place. Sometimes you will want to add a little JavaScript logic or reference a dynamic property inside that markup. In this situation, you can use curly braces in your JSX to "open a window" to JavaScript: +JSX を使うことで、JavaScript ファイル内に HTML のようなマークアップを記述し、レンダーのロジックとコンテンツを同じ場所に配置することができます。時には、そのマークアップ内でちょっとした JavaScript ロジックを追加したり、動的なプロパティを参照したりしたいことがあります。このような状況では、JSX 内で波括弧を使い JavaScript への「窓を開ける」ことができます。 @@ -229,13 +229,13 @@ body > div > div { padding: 20px; } -Read **[JavaScript in JSX with Curly Braces](/learn/javascript-in-jsx-with-curly-braces)** to learn how to access JavaScript data from JSX. +**[JSX に波括弧で JavaScript を含める](/learn/javascript-in-jsx-with-curly-braces)** を読んで、JSX 内 から JavaScript のデータにアクセスする方法を学びましょう。 -## Passing props to a component {/*passing-props-to-a-component*/} +## コンポーネントに props を渡す {/*passing-props-to-a-component*/} -React components use *props* to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, functions, and even JSX! +React コンポーネントでは、*props* を使ってお互いに情報をやり取りします。親コンポーネントは、子コンポーネントに props を与えることで、情報を渡すことができます。HTML の属性 (attribute) と似ていますが、オブジェクト、配列、関数、そして JSX まで、どのような JavaScript の値でも渡すことができます! @@ -310,15 +310,15 @@ export function getImageUrl(person, size = 's') { -Read **[Passing Props to a Component](/learn/passing-props-to-a-component)** to learn how to pass and read props. +**[コンポーネントに props を渡す](/learn/passing-props-to-a-component)** を読んで、props の渡し方と読み取り方を学びましょう。 -## Conditional rendering {/*conditional-rendering*/} +## 条件付きレンダー {/*conditional-rendering*/} -Your components will often need to display different things depending on different conditions. In React, you can conditionally render JSX using JavaScript syntax like `if` statements, `&&`, and `? :` operators. +コンポーネントは、さまざまな条件によって表示内容を切り替える必要がよくあります。React では、JavaScript の `if` 文、`&&` や `? :` 演算子などの構文を使って、条件付きで JSX をレンダーすることができます。 -In this example, the JavaScript `&&` operator is used to conditionally render a checkmark: +この例では、JavaScript の `&&` 演算子を使い、チェックマークを条件付きでレンダーしています。 @@ -358,15 +358,15 @@ export default function PackingList() { -Read **[Conditional Rendering](/learn/conditional-rendering)** to learn the different ways to render content conditionally. +**[条件付きレンダー](/learn/conditional-rendering)** を読んで、コンテンツを条件付きでレンダーするためのさまざまな方法を学びましょう。 -## Rendering lists {/*rendering-lists*/} +## リストのレンダー {/*rendering-lists*/} -You will often want to display multiple similar components from a collection of data. You can use JavaScript's `filter()` and `map()` with React to filter and transform your array of data into an array of components. +データの集まりから複数のよく似たコンポーネントを表示したいことがよくあります。React で JavaScript の `filter()` や `map()` を使って、データの配列をフィルタリングしたり、コンポーネントの配列に変換したりすることができます。 -For each array item, you will need to specify a `key`. Usually, you will want to use an ID from the database as a `key`. Keys let React keep track of each item's place in the list even if the list changes. +配列内の各要素には、`key` を指定する必要があります。通常、データベースの ID を `key` として使うことになるでしょう。key は、リストが変更されても各アイテムのリスト内の位置を React が追跡できるようにするために必要です。 @@ -458,18 +458,18 @@ h2 { font-size: 20px; } -Read **[Rendering Lists](/learn/rendering-lists)** to learn how to render a list of components, and how to choose a key. +**[リストのレンダー](/learn/rendering-lists)** を読んで、コンポーネントのリストをレンダーする方法と、key の選択方法を学びましょう。 -## Keeping components pure {/*keeping-components-pure*/} +## コンポーネントを純粋に保つ {/*keeping-components-pure*/} -Some JavaScript functions are *pure.* A pure function: +いくつかの JavaScript の関数は*純関数*です。純関数には以下の特徴があります。 -* **Minds its own business.** It does not change any objects or variables that existed before it was called. -* **Same inputs, same output.** Given the same inputs, a pure function should always return the same result. +* **自分の仕事に集中する。** 呼び出される前に存在していたオブジェクトや変数を変更しない。 +* **同じ入力には同じ出力。** 同じ入力を与えると、純関数は常に同じ結果を返す。 -By strictly only writing your components as pure functions, you can avoid an entire class of baffling bugs and unpredictable behavior as your codebase grows. Here is an example of an impure component: +コンポーネントを常に厳密に純関数として書くことで、コードベースが成長するにつれて起きがちな、あらゆる種類の不可解なバグ、予測不可能な挙動を回避することができます。以下は純粋ではないコンポーネントの例です。 @@ -495,7 +495,7 @@ export default function TeaSet() { -You can make this component pure by passing a prop instead of modifying a preexisting variable: +このコンポーネントを純粋にするには、既に存在する変数を書き換えるのではなく、prop を渡すようにすることができます。 @@ -519,12 +519,12 @@ export default function TeaSet() { -Read **[Keeping Components Pure](/learn/keeping-components-pure)** to learn how to write components as pure, predictable functions. +**[コンポーネントを純粋に保つ](/learn/keeping-components-pure)** を読んで、予測可能な純関数としてコンポーネントを作成する方法を学びましょう。 -## What's next? {/*whats-next*/} +## 次のステップ {/*whats-next*/} -Head over to [Your First Component](/learn/your-first-component) to start reading this chapter page by page! +[初めてのコンポーネント](/learn/your-first-component) に進んで、この章をページごとに読み進めましょう! -Or, if you're already familiar with these topics, why not read about [Adding Interactivity](/learn/adding-interactivity)? +もしくは、すでにこれらのトピックに詳しい場合、[インタラクティビティの追加](/learn/adding-interactivity) について読んでみましょう。 diff --git a/src/content/learn/keeping-components-pure.md b/src/content/learn/keeping-components-pure.md index 60760edc5..9730adc38 100644 --- a/src/content/learn/keeping-components-pure.md +++ b/src/content/learn/keeping-components-pure.md @@ -1,41 +1,41 @@ --- -title: Keeping Components Pure +title: コンポーネントを純粋に保つ --- -Some JavaScript functions are *pure.* Pure functions only perform a calculation and nothing more. By strictly only writing your components as pure functions, you can avoid an entire class of baffling bugs and unpredictable behavior as your codebase grows. To get these benefits, though, there are a few rules you must follow. +JavaScript 関数の中には、*純関数* (pure function) と呼ばれるものがあります。純関数とは計算だけを行い、他には何もしない関数のことです。コンポーネントを常に厳密に純関数として書くことで、コードベースが成長するにつれて起きがちな、あらゆる種類の不可解なバグ、予測不可能な挙動を回避することができます。ただし、このようなメリットを得るためには、従わなければならないルールがいくつか存在します。 -* What purity is and how it helps you avoid bugs -* How to keep components pure by keeping changes out of the render phase -* How to use Strict Mode to find mistakes in your components +* 「純粋」であるとは何か、それによりなぜバグが減らせるのか +* 変更をレンダーの外で行い、コンポーネントを純粋に保つ方法 +* Strict Mode を使用してコンポーネントの間違いを見つける方法 -## Purity: Components as formulas {/*purity-components-as-formulas*/} +## 純粋性:コンポーネントとは数式のようなもの {/*purity-components-as-formulas*/} -In computer science (and especially the world of functional programming), [a pure function](https://wikipedia.org/wiki/Pure_function) is a function with the following characteristics: +コンピュータサイエンス(特に関数型プログラミングの世界)では、[純関数 (pure function)](https://wikipedia.org/wiki/Pure_function) とは、以下のような特徴を持つ関数のことを指します。 -* **It minds its own business.** It does not change any objects or variables that existed before it was called. -* **Same inputs, same output.** Given the same inputs, a pure function should always return the same result. +* **自分の仕事に集中する。** 呼び出される前に存在していたオブジェクトや変数を変更しない。 +* **同じ入力には同じ出力。** 同じ入力を与えると、純関数は常に同じ結果を返す。 -You might already be familiar with one example of pure functions: formulas in math. +皆さんは純関数の例をひとつ、すでにご存知のはずです。数学における関数です。 -Consider this math formula: y = 2x. +この数式を考えてみてください:y = 2x。 -If x = 2 then y = 4. Always. +もし x = 2 ならば y = 4。常にです。 -If x = 3 then y = 6. Always. +もし x = 3 ならば y = 6。常にです。 -If x = 3, y won't sometimes be 9 or –1 or 2.5 depending on the time of day or the state of the stock market. +もし x = 3 ならば、 y が現在時刻や株式市況に影響されてたまに 9–12.5 になったりはしません。 -If y = 2x and x = 3, y will _always_ be 6. +もし y = 2x かつ x = 3 なら、y は*どんな場合でも常に* 6 になるのです。 -If we made this into a JavaScript function, it would look like this: +この式を JavaScript 関数で書くとすると、次のようになります: ```js function double(number) { @@ -43,9 +43,9 @@ function double(number) { } ``` -In the above example, `double` is a **pure function.** If you pass it `3`, it will return `6`. Always. +上記の例では、 `double` 関数は**純関数**です。もし `3` を渡すと、`6` を返しますね。常にです。 -React is designed around this concept. **React assumes that every component you write is a pure function.** This means that React components you write must always return the same JSX given the same inputs: +React はこのような概念に基づいて設計されています。**React は、あなたが書くすべてのコンポーネントが純関数であると仮定しています。** つまり、あなたが書く React コンポーネントは、与えられた入力が同じであれば、常に同じ JSX を返す必要があります。 @@ -75,21 +75,21 @@ export default function App() { -When you pass `drinkers={2}` to `Recipe`, it will return JSX containing `2 cups of water`. Always. +`drinkers={2}` を `Recipe` に渡すと、`2 cups of water` を含む JSX が返されます。常にです。 -If you pass `drinkers={4}`, it will return JSX containing `4 cups of water`. Always. +`drinkers={4}` を渡すと、`4 cups of water` を含む JSX が返されます。常にです。 -Just like a math formula. +そう、まるで数式のように、です。 -You could think of your components as recipes: if you follow them and don't introduce new ingredients during the cooking process, you will get the same dish every time. That "dish" is the JSX that the component serves to React to [render.](/learn/render-and-commit) +コンポーネントとはレシピのようなものだと考えることもできるでしょう。調理途中で新しい食材を加えたりせず、レシピに従っておけば、常に同じ料理を得ることができます。その「料理」とは、コンポーネントが React に提供する JSX のことであり、それを React が[表示](/learn/render-and-commit)します。 - + -## Side Effects: (un)intended consequences {/*side-effects-unintended-consequences*/} +## 副作用:意図せぬ (?) 付随処理 {/*side-effects-unintended-consequences*/} -React's rendering process must always be pure. Components should only *return* their JSX, and not *change* any objects or variables that existed before rendering—that would make them impure! +React のレンダープロセスは常に純粋である必要があります。コンポーネントは JSX を*返す*だけであり、レンダー前に存在していたオブジェクトや変数を*書き換え*しないようにしなければなりません。さもなくばコンポーネントは不純 (impure) になってしまいます! -Here is a component that breaks this rule: +以下は、この規則を守っていないコンポーネントの例です。 @@ -115,11 +115,11 @@ export default function TeaSet() { -This component is reading and writing a `guest` variable declared outside of it. This means that **calling this component multiple times will produce different JSX!** And what's more, if _other_ components read `guest`, they will produce different JSX, too, depending on when they were rendered! That's not predictable. +このコンポーネントは、外部で宣言された `guest` 変数を読み書きしています。つまり、**このコンポーネントを複数回呼び出すと、異なる JSX が生成されます!** さらに悪いことに、*ほかの*コンポーネントも `guest` を読み取る場合、それらもレンダーされたタイミングによって異なる JSX を生成することになります! これでは予測不可能です。 -Going back to our formula y = 2x, now even if x = 2, we cannot trust that y = 4. Our tests could fail, our users would be baffled, planes would fall out of the sky—you can see how this would lead to confusing bugs! +数式 y = 2x の例に戻ると、これは x = 2 であっても y = 4 であることが保証されない、というようなことです。テストは失敗し、ユーザは当惑し、飛行機も空から墜落しかねません。こんなことをするとなぜ混乱するバグが引き起こされるのか、もうおわかりですね。 -You can fix this component by [passing `guest` as a prop instead](/learn/passing-props-to-a-component): +[props を使って `guest` を渡す](/learn/passing-props-to-a-component)ようにこのコンポーネントを修正できます。 @@ -141,31 +141,31 @@ export default function TeaSet() { -Now your component is pure, as the JSX it returns only depends on the `guest` prop. +これでこのコンポーネントは純粋になります。返す JSX が `guest` プロパティのみに依存しているからです。 -In general, you should not expect your components to be rendered in any particular order. It doesn't matter if you call y = 2x before or after y = 5x: both formulas will resolve independently of each other. In the same way, each component should only "think for itself", and not attempt to coordinate with or depend upon others during rendering. Rendering is like a school exam: each component should calculate JSX on their own! +一般に、特定の順序でコンポーネントがレンダーされることを期待してはいけません。y = 2xy = 5x のどちらを先に呼ぶかなど問題にしてはいけないのです。これらの数式は互いに無関係に計算されるべきです。同じように、各コンポーネントは「自分のことだけを考える」べきであり、レンダーの最中に他のコンポーネントに依存したり他のコンポーネントと協調したりすることはありません。レンダーとは学校の試験のようなものです。各コンポーネントはそれぞれ、自分の力だけで JSX を計算する必要があるのです! -#### Detecting impure calculations with StrictMode {/*detecting-impure-calculations-with-strict-mode*/} +#### StrictMode で純粋でない計算を検出 {/*detecting-impure-calculations-with-strict-mode*/} -Although you might not have used them all yet, in React there are three kinds of inputs that you can read while rendering: [props](/learn/passing-props-to-a-component), [state](/learn/state-a-components-memory), and [context.](/learn/passing-data-deeply-with-context) You should always treat these inputs as read-only. +まだ全部を使ったことはないかもしれませんが、React には [props](/learn/passing-props-to-a-component)、[state](/learn/state-a-components-memory)、そして[コンテクスト](/learn/passing-data-deeply-with-context)という、レンダー中に読み取ることができる 3 種類の入力があります。これらの入力は常に読み取り専用として扱うようにしてください。 -When you want to *change* something in response to user input, you should [set state](/learn/state-a-components-memory) instead of writing to a variable. You should never change preexisting variables or objects while your component is rendering. +ユーザー入力に応じて何かを *変更* したい場合は、変数に書き込む代わりに、[state を設定する](/learn/state-a-components-memory)ことが適切です。要素のレンダー中に既存の変数やオブジェクトを書き換えることは絶対にやってはいけません。 -React offers a "Strict Mode" in which it calls each component's function twice during development. **By calling the component functions twice, Strict Mode helps find components that break these rules.** +React には "Strict Mode" という機能があり、開発中には各コンポーネント関数を 2 回呼び出します。**関数呼び出しを 2 回行うことで、Strict Mode はこれらのルールに反するコンポーネントを見つけるのに役立ちます。** -Notice how the original example displayed "Guest #2", "Guest #4", and "Guest #6" instead of "Guest #1", "Guest #2", and "Guest #3". The original function was impure, so calling it twice broke it. But the fixed pure version works even if the function is called twice every time. **Pure functions only calculate, so calling them twice won't change anything**--just like calling `double(2)` twice doesn't change what's returned, and solving y = 2x twice doesn't change what y is. Same inputs, same outputs. Always. +元の例では "Guest #1"、"Guest #2"、"Guest #3" と表示される代わりに "Guest #2"、"Guest #4"、"Guest #6" と表示されてしまっていましたね。元の関数が純粋でなかったため、2 回呼び出すと壊れていたわけです。修正された純粋なバージョンは、毎回 2 回呼び出されても問題ありません。**純関数は計算をするだけなので、2 回呼び出しても何も変わりません**。`double(2)` を 2 回呼び出しても戻り値が変わることはなく、y = 2x を 2 回解いても y が変わることがないのと全く同じです。入力が同じならば、出力も同じにしてください。常にそうしてください。 -Strict Mode has no effect in production, so it won't slow down the app for your users. To opt into Strict Mode, you can wrap your root component into ``. Some frameworks do this by default. +Strict Mode は本番環境では影響を与えないため、ユーザが使うアプリを遅くすることはありません。Strict Mode を有効にするには、ルートコンポーネントを `` でラップします。一部のフレームワークでは、これがデフォルトで行われます。 -### Local mutation: Your component's little secret {/*local-mutation-your-components-little-secret*/} +### ローカルミューテーション:コンポーネントの小さな秘密 {/*local-mutation-your-components-little-secret*/} -In the above example, the problem was that the component changed a *preexisting* variable while rendering. This is often called a **"mutation"** to make it sound a bit scarier. Pure functions don't mutate variables outside of the function's scope or objects that were created before the call—that makes them impure! +上記の例では、問題はコンポーネントがレンダーの最中に*既存*の変数を変更していた点にありました。このような変更は、少し恐ろしい言い方では **"ミューテーション(変異; mutation)"** と呼ばれます。純関数は、関数のスコープ外の変数や、呼び出し前に作成されたオブジェクトをミューテートしません。そういうことをしてしまった関数は「不純」になってしまいます! -However, **it's completely fine to change variables and objects that you've *just* created while rendering.** In this example, you create an `[]` array, assign it to a `cups` variable, and then `push` a dozen cups into it: +しかし、**レンダー中に*その場で*作成した変数やオブジェクトであれば、書き換えることは全く問題ありません。** この例では、`[]` 配列を作成して `cups` 変数に代入し、それに 12 個のカップを `push` しています: @@ -185,43 +185,43 @@ export default function TeaGathering() { -If the `cups` variable or the `[]` array were created outside the `TeaGathering` function, this would be a huge problem! You would be changing a *preexisting* object by pushing items into that array. +`cups` 変数または `[]` 配列が `TeaGathering` 関数の外で作成されたものだった場合、これは大きな問題になることでしょう! *既存の*オブジェクトを変更してしまうことになるからです。 -However, it's fine because you've created them *during the same render*, inside `TeaGathering`. No code outside of `TeaGathering` will ever know that this happened. This is called **"local mutation"**—it's like your component's little secret. +しかし、`cups` 変数と `[]` 配列は、`TeaGathering` 内で*同一のレンダー中に*作成されたものであるため、問題はありません。`TeaGathering` 以外のコードは、これが起こったことすら知るすべがありません。これは "ローカルミューテーション (local mutation)" と呼ばれます。あなたのコンポーネント内のちょっとした秘密のようなものです。 -## Where you _can_ cause side effects {/*where-you-_can_-cause-side-effects*/} +## 副作用を引き起こせる場所 {/*where-you-_can_-cause-side-effects*/} -While functional programming relies heavily on purity, at some point, somewhere, _something_ has to change. That's kind of the point of programming! These changes—updating the screen, starting an animation, changing the data—are called **side effects.** They're things that happen _"on the side"_, not during rendering. +関数型プログラミングには純粋性が重要であるとはいえ、いつか、どこかの場所で、*何らかのもの*が変化しなければなりません。むしろそれがプログラミングをする意味というものでしょう。これらの変化(スクリーンの更新、アニメーションの開始、データの変更など)は **副作用 (side effect)** と呼ばれます。レンダーの最中には発生しない、「付随的」なものです。 -In React, **side effects usually belong inside [event handlers.](/learn/responding-to-events)** Event handlers are functions that React runs when you perform some action—for example, when you click a button. Even though event handlers are defined *inside* your component, they don't run *during* rendering! **So event handlers don't need to be pure.** +React では、**副作用は通常、[イベントハンドラ](/learn/responding-to-events)の中に属します**。イベントハンドラは、ボタンがクリックされたといった何らかのアクションが実行されたときに React が実行する関数です。イベントハンドラは、コンポーネントの「内側」で定義されているものではありますが、レンダーの「最中」に実行されるわけではありません! **つまり、イベントハンドラは純粋である必要はありません。** -If you've exhausted all other options and can't find the right event handler for your side effect, you can still attach it to your returned JSX with a [`useEffect`](/reference/react/useEffect) call in your component. This tells React to execute it later, after rendering, when side effects are allowed. **However, this approach should be your last resort.** +いろいろ探してもあなたの副作用を書くのに適切なイベントハンドラがどうしても見つからない場合は、コンポーネントから返された JSX に [`useEffect`](/reference/react/useEffect) 呼び出しを付加することで副作用を付随させることも可能です。これにより React に、その関数をレンダーの後(その時点なら副作用が許されます)で呼ぶように指示できます。**ただしこれは最終手段であるべきです。** -When possible, try to express your logic with rendering alone. You'll be surprised how far this can take you! +可能な限り、ロジックをレンダーのみで表現してみてください。これだけでどれだけのことができるのか、驚くことでしょう! -#### Why does React care about purity? {/*why-does-react-care-about-purity*/} +#### React はなぜ純粋性を重視するのか? {/*why-does-react-care-about-purity*/} -Writing pure functions takes some habit and discipline. But it also unlocks marvelous opportunities: +純関数を書くことには、多少の習慣化と訓練が必要です。しかし、それは素晴らしいチャンスをもたらすものでもあります。 -* Your components could run in a different environment—for example, on the server! Since they return the same result for the same inputs, one component can serve many user requests. -* You can improve performance by [skipping rendering](/reference/react/memo) components whose inputs have not changed. This is safe because pure functions always return the same results, so they are safe to cache. -* If some data changes in the middle of rendering a deep component tree, React can restart rendering without wasting time to finish the outdated render. Purity makes it safe to stop calculating at any time. +* コンポーネントが異なる環境、例えばサーバ上でも実行できるようになります! 入力値が同じなら同じ結果を返すので、ひとつのコンポーネントが多数のユーザリクエストを処理できます。 +* 入力値が変化しない場合、[レンダーをスキップ](/reference/react/memo)することでパフォーマンスを向上できます。これが問題ないのは、純関数は常に同じ出力を返すため安全にキャッシュできるからです。 +* 深いコンポーネントツリーのレンダーの途中でデータが変化した場合、React は既に古くなったレンダー処理を最後まで終わらせるような無駄を省き、新しいレンダーを開始できます。純粋性のおかげで、いつ計算を中断しても問題ありません。 -Every new React feature we're building takes advantage of purity. From data fetching to animations to performance, keeping components pure unlocks the power of the React paradigm. +我々が開発する React の新たな機能は常に、関数の純粋性を活用しています。データ取得からアニメーション、パフォーマンスの向上に到るまで、React パラダイムの威力はコンポーネントを純関数に保つことによって発揮されるのです。 -* A component must be pure, meaning: - * **It minds its own business.** It should not change any objects or variables that existed before rendering. - * **Same inputs, same output.** Given the same inputs, a component should always return the same JSX. -* Rendering can happen at any time, so components should not depend on each others' rendering sequence. -* You should not mutate any of the inputs that your components use for rendering. That includes props, state, and context. To update the screen, ["set" state](/learn/state-a-components-memory) instead of mutating preexisting objects. -* Strive to express your component's logic in the JSX you return. When you need to "change things", you'll usually want to do it in an event handler. As a last resort, you can `useEffect`. -* Writing pure functions takes a bit of practice, but it unlocks the power of React's paradigm. +* コンポーネントは純粋である必要がある。すなわち: + * **コンポーネントは自分の仕事に集中する。** レンダー前に存在していたオブジェクトや変数を書き換えない。 + * **入力が同じなら出力も同じ。** 同じ入力に対しては、常に同じ JSX を返すようにする。 +* レンダーはいつでも起こる可能性があるため、コンポーネントは相互の呼び出し順に依存してはいけない。 +* コンポーネントがレンダーに使用する入力値を書き換えない。これには props、state、コンテクストも含まれる。画面を更新するためには既存のオブジェクトを書き換えるのではなく、代わりに [state を設定する](/learn/state-a-components-memory)。 +* コンポーネントのロジックはできるだけコンポーネントが返す JSX の中で表現する。何かを「変える」必要がある場合、通常はイベントハンドラで行う。最終手段として `useEffect` を使用する。 +* 純関数を書くことには訓練が必要だが、それにより React パラダイムの威力が発揮される。 @@ -229,15 +229,15 @@ Every new React feature we're building takes advantage of purity. From data fetc -#### Fix a broken clock {/*fix-a-broken-clock*/} +#### 壊れた時計を修理 {/*fix-a-broken-clock*/} -This component tries to set the `

    `'s CSS class to `"night"` during the time from midnight to six hours in the morning, and `"day"` at all other times. However, it doesn't work. Can you fix this component? +このコンポーネントは、深夜 0 時から朝 6 時までの間は `

    ` の CSS クラスを `"night"` に、その他の時間帯は `"day"` に設定しようとしています。ですが失敗してしまっています。このコンポーネントを修正してみてください。 -You can verify whether your solution works by temporarily changing the computer's timezone. When the current time is between midnight and six in the morning, the clock should have inverted colors! +あなたの回答が機能しているかを確認するには、一時的にコンピュータのタイムゾーンを変更することで確認できます。現在の時刻が午前 0 時から 6 時までの場合、時計の色が反転するはずです! -Rendering is a *calculation*, it shouldn't try to "do" things. Can you express the same idea differently? +レンダーは計算のみを行います。そこで何かを「行おう」としてはいけません。同じ意味を表現する別の方法はありますか? @@ -301,7 +301,7 @@ body > * { -You can fix this component by calculating the `className` and including it in the render output: +`className` を計算してレンダーの出力に含めるようにすれば、このコンポーネントを修正できます。 @@ -362,19 +362,19 @@ body > * { -In this example, the side effect (modifying the DOM) was not necessary at all. You only needed to return JSX. +この例では、副作用(DOM の変更)は全く必要ではありませんでした。単に JSX を返すだけで十分です。 -#### Fix a broken profile {/*fix-a-broken-profile*/} +#### 壊れたプロフィールを修正する {/*fix-a-broken-profile*/} -Two `Profile` components are rendered side by side with different data. Press "Collapse" on the first profile, and then "Expand" it. You'll notice that both profiles now show the same person. This is a bug. +異なるデータを持つ 2 つの `Profile` コンポーネントが並んで表示されています。最初のプロファイルを折りたたみ (Collapse) してから展開 (Expand) してみてください。両方のプロファイルが同じ人物を表示することがわかります。これはバグです。 -Find the cause of the bug and fix it. +バグの原因を探し、修正してください。 -The buggy code is in `Profile.js`. Make sure you read it all from top to bottom! +バグがあるコードは `Profile.js` にあります。一番上から一番下まで読み通してください。 @@ -475,9 +475,9 @@ h1 { margin: 5px; font-size: 18px; } -The problem is that the `Profile` component writes to a preexisting variable called `currentPerson`, and the `Header` and `Avatar` components read from it. This makes *all three of them* impure and difficult to predict. +問題は、`Profile` コンポーネントが既存の `currentPerson` 変数に書き込み、`Header` と `Avatar` コンポーネントがそれを読み取っていることです。これにより、*これら 3 つのコンポーネントすべて*が不純なものとなり、予測困難となってしまっています。 -To fix the bug, remove the `currentPerson` variable. Instead, pass all information from `Profile` to `Header` and `Avatar` via props. You'll need to add a `person` prop to both components and pass it all the way down. +バグを修正するには、`currentPerson` 変数を削除します。代わりに、`Header` と `Avatar` にすべての情報を props で伝えます。両コンポーネントで `person` プロパティを追加し、それを渡す必要があります。 @@ -571,15 +571,15 @@ h1 { margin: 5px; font-size: 18px; } -Remember that React does not guarantee that component functions will execute in any particular order, so you can't communicate between them by setting variables. All communication must happen through props. +React ではコンポーネント関数が何らかの特定の順序で実行されることは保証されていないため、変数を設定してコンポーネント間でデータをやりとりすることはできない、ということを覚えておきましょう。すべての通信は props を介して行う必要があります。 -#### Fix a broken story tray {/*fix-a-broken-story-tray*/} +#### 壊れたストーリートレイを修正 {/*fix-a-broken-story-tray*/} -The CEO of your company is asking you to add "stories" to your online clock app, and you can't say no. You've written a `StoryTray` component that accepts a list of `stories`, followed by a "Create Story" placeholder. +あなたの会社の CEO に、オンライン時計アプリに「ストーリー」を追加するよう要求され、ノーと言えない状況です。あなたは `StoryTray` コンポーネントを作成して、受け取った `stories` のリストを表示させ、末尾に "Create Story" というプレースホルダを表示することにしました。 -You implemented the "Create Story" placeholder by pushing one more fake story at the end of the `stories` array that you receive as a prop. But for some reason, "Create Story" appears more than once. Fix the issue. +"Create Story" プレースホルダーは、受け取った `stories` 配列にさらにフェイクのストーリーを 1 つ追加することで実装しました。しかし、どういうわけか "Create Story" が何度も表示されてしまっています。この問題を修正してください。 @@ -675,11 +675,11 @@ li { -Notice how whenever the clock updates, "Create Story" is added *twice*. This serves as a hint that we have a mutation during rendering--Strict Mode calls components twice to make these issues more noticeable. +時計が更新されるたびに、"Create Story" が *2 回*追加されることに気づくと、レンダー中にミューテーションが発生していることがわかるでしょ。Strict Mode は、このような問題をより目立たせるために、コンポーネントを 2 回呼び出します。 -`StoryTray` function is not pure. By calling `push` on the received `stories` array (a prop!), it is mutating an object that was created *before* `StoryTray` started rendering. This makes it buggy and very difficult to predict. +問題は `StoryTray` 関数が純粋でないことです。受け取った `stories` 配列(props の一部です)に `push` を呼び出すことで、`StoryTray` がレンダーし始める*前に*作成されたオブジェクトをミューテートしてしまっています。これにより、バグや予測困難な動作につながります。 -The simplest fix is to not touch the array at all, and render "Create Story" separately: +最も単純な修正方法は、受け取った配列を一切いじらず、"Creawte Story" を別にレンダーすることです。 @@ -763,7 +763,7 @@ li { -Alternatively, you could create a _new_ array (by copying the existing one) before you push an item into it: +あるいは、アイテムを追加する前に、(すでに存在する配列をコピーすることで)*新しい*配列を生成しても構いません。 @@ -855,9 +855,9 @@ li { -This keeps your mutation local and your rendering function pure. However, you still need to be careful: for example, if you tried to change any of the array's existing items, you'd have to clone those items too. +これにより、あなたのミューテーションはローカルなものとなり、レンダー関数が純粋に保たれます。ただしまだ注意が必要です。たとえば、配列の既存のアイテムを変更したい場合、そのアイテム自体も複製する必要があるでしょう。 -It is useful to remember which operations on arrays mutate them, and which don't. For example, `push`, `pop`, `reverse`, and `sort` will mutate the original array, but `slice`, `filter`, and `map` will create a new one. +配列に対する操作のうちどれが配列の書き換えを伴い、どれが伴わないかを覚えておくことは有用です。例えば `push`、`pop`、`reverse`、`sort` は元の配列を書き換えてしまいますが、`slice`、`filter`、`map` は新しい配列を作成します。 diff --git a/src/content/learn/rendering-lists.md b/src/content/learn/rendering-lists.md index 45b60240b..9d9d070a7 100644 --- a/src/content/learn/rendering-lists.md +++ b/src/content/learn/rendering-lists.md @@ -1,24 +1,24 @@ --- -title: Rendering Lists +title: リストのレンダー --- -You will often want to display multiple similar components from a collection of data. You can use the [JavaScript array methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#) to manipulate an array of data. On this page, you'll use [`filter()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and [`map()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map) with React to filter and transform your array of data into an array of components. +データの集まりから、似たようなコンポーネントを複数表示させたいことがあります。データの配列を操作するには [JavaScript の配列メソッド](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#)が使えます。このページでは [`filter()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) や [`map()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map) を React で使用して、データの配列をフィルタリングしたり、コンポーネントの配列に変換したりする方法を見ていきましょう。 -* How to render components from an array using JavaScript's `map()` -* How to render only specific components using JavaScript's `filter()` -* When and why to use React keys +* JavaScript の `map()` を使用して、配列からコンポーネントをレンダーする方法 +* JavaScript の `filter()` を使用して、特定のコンポーネントのみをレンダーする方法 +* React での key の使用方法と、その必要性 -## Rendering data from arrays {/*rendering-data-from-arrays*/} +## 配列からデータをレンダー {/*rendering-data-from-arrays*/} -Say that you have a list of content. +以下のようなコンテンツのリストがあるとしましょう。 ```js
      @@ -30,11 +30,11 @@ Say that you have a list of content.
    ``` -The only difference among those list items is their contents, their data. You will often need to show several instances of the same component using different data when building interfaces: from lists of comments to galleries of profile images. In these situations, you can store that data in JavaScript objects and arrays and use methods like [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [`filter()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) to render lists of components from them. +これらのリスト項目は、その中身、すなわちデータのみが異なっています。インターフェースを構築する際にはよく、コメント一覧やプロフィール画像のギャラリーなどのように、異なるデータを使用して同じコンポーネントの複数のインスタンスを表示する必要があります。このような場合、JavaScript のオブジェクトや配列にそのデータを保存し、[`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) や [`filter()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) などのメソッドを使ってコンポーネントのリストをレンダーすることができます。 -Here’s a short example of how to generate a list of items from an array: +以下は、配列からアイテムのリストを生成する方法を示す簡単な例です。 -1. **Move** the data into an array: +1. データを配列に**移動**します: ```js const people = [ @@ -46,19 +46,19 @@ const people = [ ]; ``` -2. **Map** the `people` members into a new array of JSX nodes, `listItems`: +2. `people` 内のメンバを `listItems` という新しい JSX の配列に**マップ**します: ```js const listItems = people.map(person =>
  • {person}
  • ); ``` -3. **Return** `listItems` from your component wrapped in a `
      `: +3. コンポーネントから `listItems` を `
        ` で囲んで返します: ```js return
          {listItems}
        ; ``` -Here is the result: +以下が結果です: @@ -85,7 +85,7 @@ li { margin-bottom: 10px; } -Notice the sandbox above displays a console error: +上のサンドボックスには、コンソールエラーが表示されています: @@ -93,11 +93,11 @@ Warning: Each child in a list should have a unique "key" prop. -You'll learn how to fix this error later on this page. Before we get to that, let's add some structure to your data. +このエラーを修正する方法についてはこのページの後半で説明します。その前に、このデータに構造を追加しましょう。 -## Filtering arrays of items {/*filtering-arrays-of-items*/} +## アイテムの配列をフィルタする {/*filtering-arrays-of-items*/} -This data can be structured even more. +このデータにさらに構造を加えてみました。 ```js const people = [{ @@ -121,11 +121,11 @@ const people = [{ }]; ``` -Let's say you want a way to only show people whose profession is `'chemist'`. You can use JavaScript's `filter()` method to return just those people. This method takes an array of items, passes them through a “test” (a function that returns `true` or `false`), and returns a new array of only those items that passed the test (returned `true`). +ここで、職業 (profession) が `'chemist'` の人だけを表示したいとしましょう。JavaScript の `filter()` メソッドを使用すれば、そのような職業の人だけを返すことができます。このメソッドは、要素の配列を受け取り、個々の要素を「テスト」(`true` または `false` を返す関数)にかけ、そして、テストを通過した要素(テスト関数が `true` を返したもの)のみを含む配列を返します。 -You only want the items where `profession` is `'chemist'`. The "test" function for this looks like `(person) => person.profession === 'chemist'`. Here's how to put it together: +`profession` が `'chemist'` となっている要素のみが必要でした。そのための「テスト」関数は、`(person) => person.profession === 'chemist'` のようになります。使い方の全体像は以下のようになります。 -1. **Create** a new array of just “chemist” people, `chemists`, by calling `filter()` on the `people` filtering by `person.profession === 'chemist'`: +1. `people` に対して `filter()` を呼び出し、`person.profession === 'chemist'` を使ってフィルタした、職業が "chemist" である人物のみの新しい配列を**作成**します。 ```js const chemists = people.filter(person => @@ -133,7 +133,7 @@ const chemists = people.filter(person => ); ``` -2. Now **map** over `chemists`: +2. 次に `chemists` に対して **map** を適用します: ```js {1,13} const listItems = chemists.map(person => @@ -151,7 +151,7 @@ const listItems = chemists.map(person => ); ``` -3. Lastly, **return** the `listItems` from your component: +3. 最後に、コンポーネントから `listItems` を**返し**ます。 ```js return
          {listItems}
        ; @@ -244,7 +244,7 @@ img { width: 100px; height: 100px; border-radius: 50%; } -Arrow functions implicitly return the expression right after `=>`, so you didn't need a `return` statement: +アロー関数は `=>` の直後の式を自動的に返しますので、`return` 文を直接書く必要はありません: ```js const listItems = chemists.map(person => @@ -252,7 +252,7 @@ const listItems = chemists.map(person => ); ``` -However, **you must write `return` explicitly if your `=>` is followed by a `{` curly brace!** +ただし、もし `=>` の次に `{` が続く場合は、**必ず `return` 文を明示的に書く必要があります**。 ```js const listItems = chemists.map(person => { // Curly brace @@ -260,13 +260,13 @@ const listItems = chemists.map(person => { // Curly brace }); ``` -Arrow functions containing `=> {` are said to have a ["block body".](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#function_body) They let you write more than a single line of code, but you *have to* write a `return` statement yourself. If you forget it, nothing gets returned! +`=> {` を含むアロー関数は ["ブロック形式の関数本体"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#function_body) を持つものとして扱われます。これにより複数行のコードが書けるようになりますが、`return` 文を自分で書かなければなりません。書き忘れた場合は何も返されません! -## Keeping list items in order with `key` {/*keeping-list-items-in-order-with-key*/} +## `key` によるリストアイテムの順序の保持 {/*keeping-list-items-in-order-with-key*/} -Notice that all the sandboxes above show an error in the console: +上記のすべてのサンドボックスで、コンソールにエラーが表示されていることに注目しましょう: @@ -274,7 +274,7 @@ Warning: Each child in a list should have a unique "key" prop. -You need to give each array item a `key` -- a string or a number that uniquely identifies it among other items in that array: +配列の各アイテムには、`key` を渡す必要があります。配列内の他のアイテムと区別できるようにするための一意な文字列ないし数値のことです。 ```js
      • ...
      • @@ -282,13 +282,13 @@ You need to give each array item a `key` -- a string or a number that uniquely i -JSX elements directly inside a `map()` call always need keys! +`map()` 内で直接 JSX 要素を使用する場合、必ず key が必要です! -Keys tell React which array item each component corresponds to, so that it can match them up later. This becomes important if your array items can move (e.g. due to sorting), get inserted, or get deleted. A well-chosen `key` helps React infer what exactly has happened, and make the correct updates to the DOM tree. +key は、配列のどの要素がどのコンポーネントに対応するのかを React が判断し、後で正しく更新するために必要です。これが重要となるのは、配列の要素が移動(ソートなどによって)した場合、挿入された場合、あるいは削除された場合です。適切に `key` を選ぶことで、React は何が起こったか推測し、DOM ツリーに正しい更新を反映させることができます。 -Rather than generating keys on the fly, you should include them in your data: +key は動的に生成するのではなく、元データに含めるべきです。 @@ -374,11 +374,11 @@ img { width: 100px; height: 100px; border-radius: 50%; } -#### Displaying several DOM nodes for each list item {/*displaying-several-dom-nodes-for-each-list-item*/} +#### リストアイテムごとに複数の DOM ノードを表示する {/*displaying-several-dom-nodes-for-each-list-item*/} -What do you do when each item needs to render not one, but several DOM nodes? +各アイテムが 1 つの DOM ノードではなく、複数の DOM ノードをレンダーする必要がある場合はどうするのでしょうか? -The short [`<>...` Fragment](/reference/react/Fragment) syntax won't let you pass a key, so you need to either group them into a single `
        `, or use the slightly longer and [more explicit `` syntax:](/reference/react/Fragment#rendering-a-list-of-fragments) +短い [`<>...` フラグメント](/reference/react/Fragment)構文では `key` を渡せないため、これらを 1 つの `
        ` にグループ化するか、やや長くて[より明示的な `` シンタックス](/reference/react/Fragment#rendering-a-list-of-fragments)を使用する必要があります: ```js import { Fragment } from 'react'; @@ -393,46 +393,46 @@ const listItems = people.map(person => ); ``` -Fragments disappear from the DOM, so this will produce a flat list of `

        `, `

        `, `

        `, `

        `, and so on. +フラグメントは DOM から消え去るため、これにより `

        `、`

        `、`

        `、`

        ` というように続くフラットなリストが生成されます。 -### Where to get your `key` {/*where-to-get-your-key*/} +### `key` をどこから得るのか {/*where-to-get-your-key*/} -Different sources of data provide different sources of keys: +データソースの種類によって key を得る方法は異なります。 -* **Data from a database:** If your data is coming from a database, you can use the database keys/IDs, which are unique by nature. -* **Locally generated data:** If your data is generated and persisted locally (e.g. notes in a note-taking app), use an incrementing counter, [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID) or a package like [`uuid`](https://www.npmjs.com/package/uuid) when creating items. +* **データベースからのデータ:** データがデータベースから来る場合、データベースのキーや ID は必然的に一意ですので、それを利用できます。 +* **ローカルで生成されたデータ:** データがローカルで生成されて保持される場合(例:ノートを取るアプリにおけるノート)は、アイテムを作成する際に、インクリメンタルなカウンタや [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID)、または [`uuid`](https://www.npmjs.com/package/uuid) などのパッケージを使用します。 -### Rules of keys {/*rules-of-keys*/} +### `key` のルール {/*rules-of-keys*/} -* **Keys must be unique among siblings.** However, it’s okay to use the same keys for JSX nodes in _different_ arrays. -* **Keys must not change** or that defeats their purpose! Don't generate them while rendering. +* **キーは兄弟間で一意でなければなりません。** ただし、*異なる*配列に対応する JSX ノードには同じキーを使用することができます。 +* **キーは変更してはいけません。** さもないと `key` の目的が台無しになります。レンダーの最中に key を生成してはいけません。 -### Why does React need keys? {/*why-does-react-need-keys*/} +### なぜ React は `key` を必要とするのか {/*why-does-react-need-keys*/} -Imagine that files on your desktop didn't have names. Instead, you'd refer to them by their order -- the first file, the second file, and so on. You could get used to it, but once you delete a file, it would get confusing. The second file would become the first file, the third file would be the second file, and so on. +デスクトップ上のファイルに名前がない場合を想像してください。代わりに、最初のファイル、2 番目のファイルといったように、順番によってそれらを区別する必要があるとしましょう。そのうち番号に慣れるかもしれませんが、ファイルを削除した途端に混乱してしまいます。2 番目のファイルが 1 番目のファイルになり、3 番目のファイルが 2 番目のファイルになり、という具合です。 -File names in a folder and JSX keys in an array serve a similar purpose. They let us uniquely identify an item between its siblings. A well-chosen key provides more information than the position within the array. Even if the _position_ changes due to reordering, the `key` lets React identify the item throughout its lifetime. +フォルダ内のファイル名と JSX の key の目的は似ています。兄弟間で項目を一意に識別できるようにするのです。適切に選択された key は、配列内の位置よりも多くの情報を提供します。並べ替えによって*位置*が変更されたとしても、`key` のおかげで React はその項目が存在する限り、それを一意に識別できるのです。 -You might be tempted to use an item's index in the array as its key. In fact, that's what React will use if you don't specify a `key` at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs. +アイテムのインデックスを `key` として使用したくなるかもしれません。実際、`key` を指定しなかった場合、React はデフォルトでインデックスを使用します。しかし、アイテムが挿入されたり削除されたり、配列を並び替えたりすると、レンダーするアイテムの順序も変わります。インデックスをキーとして利用すると、微妙かつややこしいバグの原因となります。 -Similarly, do not generate keys on the fly, e.g. with `key={Math.random()}`. This will cause keys to never match up between renders, leading to all your components and DOM being recreated every time. Not only is this slow, but it will also lose any user input inside the list items. Instead, use a stable ID based on the data. +同様に、`key={Math.random()}` などとしてキーをその場で生成してはいけません。こうするとキーがレンダーごとに一切合致しなくなり、コンポーネントと DOM が毎回再作成されるようになります。これは遅くなるのみならず、リストアイテム内のユーザによる入力値も失われてしまいます。代わりに、データに紐づいた安定した ID を使用してください。 -Note that your components won't receive `key` as a prop. It's only used as a hint by React itself. If your component needs an ID, you have to pass it as a separate prop: ``. +コンポーネントは `key` を props として受け取らないということに注意してください。React 自体がヒントとして使用するだけです。コンポーネントが ID を必要とする場合は、別の props として渡す必要があります:``。 -On this page you learned: +このページでは以下のことを学びました: -* How to move data out of components and into data structures like arrays and objects. -* How to generate sets of similar components with JavaScript's `map()`. -* How to create arrays of filtered items with JavaScript's `filter()`. -* Why and how to set `key` on each component in a collection so React can keep track of each of them even if their position or data changes. +* コンポーネントからデータを配列やオブジェクトといったデータ構造に移動する方法。 +* JavaScript の `map()` を使用して類似したコンポーネントの集まりを作成する方法。 +* JavaScript の `filter()` を使用してフィルタリングされたアイテムの配列を作成する方法。 +* コレクション内の各コンポーネントに `key` を設定して、位置やデータが変更された場合でも React がそれぞれを追跡できるようにする方法と、それが必要な理由。 @@ -440,11 +440,11 @@ On this page you learned: -#### Splitting a list in two {/*splitting-a-list-in-two*/} +#### リストを 2 つに分割する {/*splitting-a-list-in-two*/} -This example shows a list of all people. +この例では、すべての人物の一覧を表示しています。 -Change it to show two separate lists one after another: **Chemists** and **Everyone Else.** Like previously, you can determine whether a person is a chemist by checking if `person.profession === 'chemist'`. +それを、**化学者 (chemist)** と **その他の人** の 2 つの別々の一覧に変更してください。前に述べたように、`person.profession === 'chemist'` であるかどうかを確認することで、その人が化学者であるかどうかを決定できます。 @@ -535,7 +535,7 @@ img { width: 100px; height: 100px; border-radius: 50%; } -You could use `filter()` twice, creating two separate arrays, and then `map` over both of them: +`filter()` を 2 回使用して、2 つの別々の配列を作成し、その両方に `map` を適用します。 @@ -648,9 +648,9 @@ img { width: 100px; height: 100px; border-radius: 50%; } -In this solution, the `map` calls are placed directly inline into the parent `

          ` elements, but you could introduce variables for them if you find that more readable. +この解答では、`map` コールは親の `
            ` 要素の中に直接インラインで配置されていますが、このための変数を導入する方が読みやすいと思った場合は、そうしても構いません。 -There is still a bit duplication between the rendered lists. You can go further and extract the repetitive parts into a `` component: +レンダーされた 2 つのリストの間にはまだ少し重複部分があります。さらに進んで、反復部分を `` コンポーネントに抽出できます。 @@ -762,9 +762,9 @@ img { width: 100px; height: 100px; border-radius: 50%; } -A very attentive reader might notice that with two `filter` calls, we check each person's profession twice. Checking a property is very fast, so in this example it's fine. If your logic was more expensive than that, you could replace the `filter` calls with a loop that manually constructs the arrays and checks each person once. +注意深い方は、2 つの `filter` コールで各人物の職業を 2 回確認していることに気づくかもしれません。プロパティのチェックは非常に高速ですので、この例では問題ありません。あなたのロジックがそれ以上に重たい場合は、`filter` コールを手動のループに置き換え、各人物を一度だけチェックしながらループ内で手動で 2 つの配列を構築することができます。 -In fact, if `people` never change, you could move this code out of your component. From React's perspective, all that matters is that you give it an array of JSX nodes in the end. It doesn't care how you produce that array: +実際、`people` が一切変わらないのであれば、このコードをコンポーネントの外に移動しても構いません。React の観点からは、最終的に JSX ノードの配列が生成されていればよいのです。どのようにしてその配列を生成しているかは問題ではありません: @@ -882,13 +882,13 @@ img { width: 100px; height: 100px; border-radius: 50%; } -#### Nested lists in one component {/*nested-lists-in-one-component*/} +#### 同一コンポーネント内のネストしたリスト {/*nested-lists-in-one-component*/} -Make a list of recipes from this array! For each recipe in the array, display its name as an `

            ` and list its ingredients in a `
              `. +以下の配列から、レシピのリストを作成してください! 配列内の各レシピについて、名前を `

              ` で表示し、その材料を `
                ` を使って表示してください。 -This will require nesting two different `map` calls. +これには 2 つの異なる `map` コールをネストする必要があります。 @@ -926,7 +926,7 @@ export const recipes = [{ -Here is one way you could go about it: +以下が解決法のひとつです: @@ -972,13 +972,13 @@ export const recipes = [{ -Each of the `recipes` already includes an `id` field, so that's what the outer loop uses for its `key`. There is no ID you could use to loop over ingredients. However, it's reasonable to assume that the same ingredient won't be listed twice within the same recipe, so its name can serve as a `key`. Alternatively, you could change the data structure to add IDs, or use index as a `key` (with the caveat that you can't safely reorder ingredients). +`recipes` の各要素にはすでに `id` フィールドが含まれているので、外側のループではこれを `key` として使用します。一方で材料をループするために使用できる ID はありません。しかし、同じレシピに同じ材料が 2 度表示されることはないと考えるのが妥当ですので、材料の名前を `key` として使用することができます。あるいは、データ構造を変更して ID を追加するか、インデックスを `key` として使用することもできます(ただし、材料を安全に並べ替えることはできなくなります)。 -#### Extracting a list item component {/*extracting-a-list-item-component*/} +#### リスト要素のコンポーネントを抽出 {/*extracting-a-list-item-component*/} -This `RecipeList` component contains two nested `map` calls. To simplify it, extract a `Recipe` component from it which will accept `id`, `name`, and `ingredients` props. Where do you place the outer `key` and why? +この `RecipeList` コンポーネントは、2 つのネストした `map` 呼び出しを含んでいます。これを単純化するために、`id`, `name`, `ingredients` という props を受けとる `Recipe` コンポーネントを抽出してください。外側の `key` はどこに置きますか、またその理由は? @@ -1026,7 +1026,7 @@ export const recipes = [{ -You can copy-paste the JSX from the outer `map` into a new `Recipe` component and return that JSX. Then you can change `recipe.name` to `name`, `recipe.id` to `id`, and so on, and pass them as props to the `Recipe`: +外側の `map` から新しい `Recipe` コンポーネントに JSX をコピーペーストして、その JSX を返すことができます。そして、`recipe.name` を `name` に、`recipe.id` を `id` に変更し、`Recipe` に props として渡します: @@ -1078,15 +1078,15 @@ export const recipes = [{ -Here, `` is a syntax shortcut saying "pass all properties of the `recipe` object as props to the `Recipe` component". You could also write each prop explicitly: ``. +ここで `` というのは「 `recipe` オブジェクトのすべてのプロパティを `Recipe` コンポーネントの props として渡せ」という意味のショートカット構文です。個々の props を明示的に書いても構いません:`` -**Note that the `key` is specified on the `` itself rather than on the root `
                ` returned from `Recipe`.** This is because this `key` is needed directly within the context of the surrounding array. Previously, you had an array of `
                `s so each of them needed a `key`, but now you have an array of ``s. In other words, when you extract a component, don't forget to leave the `key` outside the JSX you copy and paste. +**`key` は `` から返される `
                ` 内ではなく、`` 自体に指定する必要があることに注意してください。** これは、`key` を直接必要としているのはそれを囲んでいる配列という文脈だからです。これまでは `
                ` の配列があったので個々の div に `key` が必要でしたが、今存在するのは `` の配列です。別の言い方をすると、コンポーネントを抽出する場合は、コピーペーストする JSX の外に `key` を残すことを忘れないようにしましょう。 -#### List with a separator {/*list-with-a-separator*/} +#### セパレータ付きリスト {/*list-with-a-separator*/} -This example renders a famous haiku by Katsushika Hokusai, with each line wrapped in a `

                ` tag. Your job is to insert an `


                ` separator between each paragraph. Your resulting structure should look like this: +この例では、葛飾北斎の有名な俳句を、各行を `

                ` タグで囲みつつ表示しています。あなたの仕事は、各段落の間に `


                ` という区切り線を挿入することです。結果はこのような形にしてください。 ```js
                @@ -1098,7 +1098,7 @@ This example renders a famous haiku by Katsushika Hokusai, with each line wrappe
                ``` -A haiku only contains three lines, but your solution should work with any number of lines. Note that `
                ` elements only appear *between* the `

                ` elements, not in the beginning or the end! +俳句は 3 行しかありませんが、あなたの答えはどのような行数であっても動作するようにしてください。`


                ` 要素は `

                ` 要素の*間*にのみ現れ、最初や最後には現れないことに注意してください! @@ -1141,17 +1141,17 @@ hr { -(This is a rare case where index as a key is acceptable because a poem's lines will never reorder.) +(俳句の行が途中で入れ替わることは決してないので、今回は特例としてインデックスを key として利用して構いません。) -You'll either need to convert `map` to a manual loop, or use a fragment. +`map` を手動のループに置き換えるか、フラグメントを使う必要があります。 -You can write a manual loop, inserting `


                ` and `

                ...

                ` into the output array as you go: +手動でループを書いて、`
                ` と `

                ...

                ` を出力用の配列に順番に入れていくという方法がとれます。 @@ -1206,9 +1206,9 @@ hr { -Using the original line index as a `key` doesn't work anymore because each separator and paragraph are now in the same array. However, you can give each of them a distinct key using a suffix, e.g. `key={i + '-text'}`. +各セパレータと段落は同じ配列に入るので、元の行インデックスを `key` として使用することはできなくなります。ですが `key={i + '-text'}` のように後ろに文字を付加することで、一意なキーを与えることができます。 -Alternatively, you could render a collection of fragments which contain `
                ` and `

                ...

                `. However, the `<>...` shorthand syntax doesn't support passing keys, so you'd have to write `` explicitly: +あるいは、`
                ` と `

                ...

                ` を含むフラグメントの配列をレンダーすることもできます。しかし、`<>...` という省略記法は key を渡すことをサポートしていないため、明示的に `` と記述する必要があります: @@ -1254,7 +1254,7 @@ hr { -Remember, fragments (often written as `<> `) let you group JSX nodes without adding extra `
                `s! +フラグメント(通常は `<> ` のように書かれる)によって、余分な `
                ` を増やさずに JSX ノードをグループ化できるということを覚えておきましょう! diff --git a/src/sidebarLearn.json b/src/sidebarLearn.json index f3d5e5dfe..ba8b4e613 100644 --- a/src/sidebarLearn.json +++ b/src/sidebarLearn.json @@ -47,7 +47,7 @@ "sectionHeader": "LEARN REACT" }, { - "title": "Describing the UI", + "title": "UI の記述", "tags": [], "path": "/learn/describing-the-ui", "routes": [ @@ -72,15 +72,15 @@ "path": "/learn/passing-props-to-a-component" }, { - "title": "Conditional Rendering", + "title": "条件付きレンダー", "path": "/learn/conditional-rendering" }, { - "title": "Rendering Lists", + "title": "リストのレンダー", "path": "/learn/rendering-lists" }, { - "title": "Keeping Components Pure", + "title": "コンポーネントを純粋に保つ", "path": "/learn/keeping-components-pure" } ]