何かを書き留める何か

数学や読んだ本について書く何かです。最近は社会人として生き残りの術を学ぶ日々です。

『Reactハンズオンラーニング 第2版』5章

Reactの門を引き続き眺める

オライリージャパンさんから頂いた『Reactハンズオンラーニング 第2版』を引き続き読み進める。

www.oreilly.co.jp

5章は「ReactとJSX」ということで、JSXを使ってコンポーネントを実装して、webpackでビルドする、という流れ。 HTMLの構造をJacaScriptで書いていく、という雰囲気。 題材としてはレシピ集である。

まずはレシピを受け取って表示するもの。

import React from "react";
import Recipe from "./Recipe";

export default function Menu({recipes}) {
    return (
        <article>
            <header>
                <h1>Delicious Recipes</h1>
            </header>
            <div className="recipes">
                {recipes.map((recipe, i) => (
                    <Recipe key={i} {...recipe} />
                ))}
            </div>
        </article>
    );
}

レシピは材料リストと工程からなる。

export default function Reecipe({name, ingredients, steps}) {
    return (
        <section id={name.toLowerCase().replace(/ /g, "-")}>
            <h1>{name}</h1>
            <IngredientsList list={ingredients}/>
            <Instructions title="Cooking Instructions" steps={steps}/>
        </section>
    );
}

そして材料リストは材料から、工程は、、、とコンポーネント単位で分解して合成していく。

最後は index.js あたりにまとめる。 実際のデータはdataディレクトリにあるJSONファイルを参照しているが、現実のアプリケーションはこれをJavaScriptで取得する、という感じになるだろう。

import React from "react";
import {render} from "react-dom";
import data from "../data/recipes.json"
import Menu from "./components/Menu";

render(<Menu recipes={data}/>, document.getElementById("root"));

HTMLのコンポーネントをJSXで分解していくのはなかなかセンスが問われるだろう、と感じた。