LoginSignup
3
3

More than 5 years have passed since last update.

React.js HelloWorldで理解するJSXの書き方(初歩的)

Last updated at Posted at 2018-01-10

React.js の勉強をはじめました。

Hello World を書いてみます。
Reactは同時にJSXも使われるようですが、JSXがあると理解するのが難しいので、はじめはJSX無しで書いてみました。

JSX無しで作ったReact.js Hello World

hw01.html
<!DOCTYPE html>
<html>
  <head>
    <script src="https://fb.me/react-15.2.0.js"></script>
    <script src="https://fb.me/react-dom-15.2.0.js"></script>
  </head>
  <body>
    <div id="app01"></div>
    <div id="app02"></div>

    <script>
      const HelloWorld = React.createClass({
        render: function() {
          return React.DOM.div({},
            'Hello World ' +
            this.props.name);
        }
      });

      const hwElement = React.createElement(HelloWorld, {name: '01'});
      ReactDOM.render(hwElement,
        document.getElementById('app01'));

      const hwFactory = React.createFactory(HelloWorld);
      ReactDOM.render(hwFactory({name: '02'}),
        document.getElementById('app02'));

    </script>

  </body>
</html>

出力結果のHTML要素は、このようになります

<body>
    <div id="app01"><div data-reactroot="">Hello World 01</div></div>
    <div id="app02"><div data-reactroot="">Hello World 02</div></div>

JSXありで作ったReact.js Hello World

hw02.js
<!DOCTYPE html>
<html>
  <head>
    <script src="https://fb.me/react-15.2.0.js"></script>
    <script src="https://fb.me/react-dom-15.2.0.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
  </head>
  <body>
    <div id="app01"></div>
    <div id="app02"></div>

    <script type="text/babel">
      const HelloWorld = React.createClass({
        render: function() {
          return <div>Hello World {this.props.name}</div>;
        }
      });

      const hwElement = <HelloWorld name="01" />;
      ReactDOM.render(hwElement,
        document.getElementById('app01'));

      ReactDOM.render(<HelloWorld name="02" />,
        document.getElementById('app02'));
    </script>


  </body>
</html>

babel-core をCDN(webでリンクするscriptのやり方) でリンクして script タグに text/babel をつけることで、script内をJSXとして解釈してくれます。

JavaScript 内にHTMLタグが含まれているのは奇妙な感じですね。

参考

[Sy] npmを使わずにReactの開発環境を構築する方法(CDNで配信されているReactとbabel-coreを利用) | Syntax Error.
https://utano.jp/entry/2016/07/react-js-load-from-cdn/

FN1608001 | React: まずは動かしてみる | HTML5 : テクニカルノート
http://www.fumiononaka.com/Business/html5/FN1608001.html

追記

サンプルが React 15.2 の例で、16.0 以降に対応していなかったので、新しい記事を書きました。

React16 CDN でHelloWorld JSXありなし両方 - Qiita
https://qiita.com/standard-software/items/0cdbcdb2a6d6355c946b

3
3
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
3
3