Open3

RSC From Scratch. Part 1: Server Components

てぃーてぃーてぃーてぃー

Node, PHPの時代はこんな感じ

<?php
  $author = "Jae Doe";
  $post_content = @file_get_contents("./posts/hello-world.txt");
?>
<html>
  <head>
    <title>My blog</title>
  </head>
  <body>
    <nav>
      <a href="/">Home</a>
      <hr>
    </nav>
    <article>
      <?php echo htmlspecialchars($post_content); ?>
    </article>
    <footer>
      <hr>
      <p><i>(c) <?php echo htmlspecialchars($author); ?>, <?php echo date("Y"); ?></i></p>
    </footer>
  </body>
</html>
てぃーてぃーてぃーてぃー

Step 1: Let's invent JSX

前の章のやり方はいちいちstringをエスケープする必要があったりしてだるかった。
当時の人達はそれを解決するためにテンプレートエンジンという方法を取った(pug, erbなど)
でも俺らにはjsxのほうが多分馴染みが深い。jsxはjavascriptにXMLを記述できるようにしたやつ。
jsxにhtmlを書くとこんな感じでパースされる

// Slightly simplified
{
  $$typeof: Symbol.for("react.element"), // Tells React it's a JSX element (e.g. <html>)
  type: 'html',
  props: {
    children: [
      {
        $$typeof: Symbol.for("react.element"),
        type: 'head',
        props: {
          children: {
            $$typeof: Symbol.for("react.element"),
            type: 'title',
            props: { children: 'My blog' }
          }
        }
      },
      {
        $$typeof: Symbol.for("react.element"),
        type: 'body',
        props: {
          children: [
            {
              $$typeof: Symbol.for("react.element"),
              type: 'nav',
              props: {
                children: [{
                  $$typeof: Symbol.for("react.element"),
                  type: 'a',
                  props: { href: '/', children: 'Home' }
                }, {
                  $$typeof: Symbol.for("react.element"),
                  type: 'hr',
                  props: null
                }]
              }
            },
            {
              $$typeof: Symbol.for("react.element"),
              type: 'article',
              props: {
                children: postContent
              }
            },
            {
              $$typeof: Symbol.for("react.element"),
              type: 'footer',
              props: {
                /* ...And so on... */
              }              
            }
          ]
        }
      }
    ]
  }
}
てぃーてぃーてぃーてぃー

Step 2: Let's invent components

入れ子のコンポーネントが動くようにちょっとjsxのレンダーの関数を変えた