13
12

More than 3 years have passed since last update.

React (JavaScript) で湯婆婆を実装してみる

Last updated at Posted at 2020-11-08

はじめに

原作者様: Javaで湯婆婆を実装してみる - Qiita

この壮大なビッグウェーブならぬビッグ湯婆婆に乗るっきゃない!

コード

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>React 湯婆婆</title>
  <script src="https://unpkg.com/react/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    (() => {
      'use strict';

      const {useState} = React;

      function Yubaba() {
        const [name, setName] = useState('');
        const newName = name.substr(Math.floor(Math.random() * name.length), 1);

        return (
          <div>
            <p>契約書だよそこに名前を書きな</p>
            <input type='text' value={name} onChange={e => setName(e.target.value)}/>
            <p>フン{name}というのかい贅沢な名だねぇ</p>
            <p>今からお前の名前は{newName}いいかい{newName}だよ分かったら返事をするんだ{newName}!!</p>
          </div>
        );
      }

      ReactDOM.render(
        <Yubaba/>,
        document.getElementById('root')
      );

    })();
  </script>
</body>
</html>

こちらがコードになります。これを textfile とかにコピペしてブラウザ起動すれば動きます。

コードの解説

湯婆婆の部屋に入る準備

React と babel を CDN で読み込む。

  <script src="https://unpkg.com/react/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone/babel.min.js"></script>

レンダー用の div 要素 (root) を記述して、あとは JS のお作法を記述する。

  <div id="root"></div>
  <script type="text/babel">
    (() => {
      'use strict';

      ...

    })();
  </script>

契約書と名前を奪う Yubaba コンポーネントを作成

Yubaba コンポーネントをつくる!
フック (useState) も使う!

      const {useState} = React;

      function Yubaba() {
        const [name, setName] = useState('');
        const newName = name.substr(Math.floor(Math.random() * name.length), 1);

        return (
          <div>
            <p>契約書だよそこに名前を書きな</p>
            <input type='text' value={name} onChange={e => setName(e.target.value)}/>
            <p>フン{name}というのかい贅沢な名だねぇ</p>
            <p>今からお前の名前は{newName}いいかい{newName}だよ分かったら返事をするんだ{newName}!!</p>
          </div>
        );
      }

      ReactDOM.render(
        <Yubaba/>,
        document.getElementById('root')
      );


実行結果

react-yubaba.png

おまけ

名前の入力が空白だった場合のクラッシュ湯婆婆は入室しませんでした!
SPA なので名前を言い終える前に湯婆婆は名前を奪い始めるという。早とちり湯婆婆降臨。

最後に

ここまで読んでいただきありがとうございました!

13
12
0

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
  3. You can use dark theme
What you can do with signing up
13
12