LoginSignup
11
13

More than 5 years have passed since last update.

Reactでリアルタイム株価表示のページを作る

Last updated at Posted at 2016-11-01

概要

  • YahooのYQLを利用して、アメリカに上場している株式のリアルタイム価格を取得
  • reactのstate管理を使って、表示させる

サンプル

11月-02-2016 04-42-22.gif

実際のコード

index.html
<!doctype html>

<html>

<head>
  <meta charset="utf-8">
  <title>react study</title>
  <script
  src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>

</head>

<body>
  <div id="content"></div>
  <script src="build.js"></script>
</body>

</html>

app.js
/*global $*/

import React from "react";
import ReactDOM from "react-dom";

var TextBox = React.createClass({
    render: function() {
        return (
            <div>
            <h2>{this.props.symbol}</h2>
            <h3>現在値{this.props.price}</h3>
            <li>ask{this.props.ask}</li>
            <li>bid{this.props.bid}</li>
            </div>
        )
    }
});

var TextData = React.createClass({
    loadPriceData: function() {
        $.ajax({
            url: "https://query.yahooapis.com/v1/public/yql?format=json&diagnostics=true&callback=",
            data: {
                q: "select * from yahoo.finance.quotes where symbol in ('MSFT', 'AAPL')",
                env: "store://datatables.org/alltableswithkeys"

            },
            dataType: "json",
            cache: false,
            success: function(data) {
                this.setState({
                    data: data.query.results.quote
                });

            }.bind(this)
        });
    },
    getInitialState: function() {
        return {
            data: [{
                "symbol": "",
                "Ask": "",
                "Bid": "",
                "LastTradePriceOnly": ""
            }]
        };
    },
    componentWillMount: function() {
        this.loadPriceData();
        setInterval(this.loadPriceData, 1000);
    },

    render: function() {
        var quotemap = this.state.data.map(function(quote) {
            return (
                <TextBox symbol={quote.symbol} ask={quote.Ask} bid={quote.Bid} price={quote.LastTradePriceOnly} key={quote.symbol}/>
            );
        });

        return (
            <div>
              {quotemap}
            </div>
        );
    }
});
// id='content'に<UserBox />を埋め込む
ReactDOM.render(
    <TextData />,
    document.getElementById('content')
);

参考

11
13
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
11
13