Perl日記

日々の知ったことのメモなどです。Perlは最近やってないです。

ReactでJSON整形ツール書いてみた

できたもの
https://dl.dropboxusercontent.com/u/9152456/json_stringify/index.html

いろいろやった後、削りまくったら結局stateしか使わなかった。

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>JSON整形ツール</title>
    style略
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.2/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.2/JSXTransformer.js"></script>
  </head>
  <body></body>
  <script type="text/jsx">
    var App = React.createClass({
      getInitialState: function() {
        return {stringifiedJson: "ここに整形されたJSONが表示されます", textValue: ""};
      },
      onChange: function(e) {
        var text = e.target.value;
        this.setState({textValue: text});
        if (text == "") {
          return;
        }

        try {
          var json = JSON.parse(text);
          this.setState({stringifiedJson: JSON.stringify(json, null, "  ")});
        }
        catch(e) {
          this.setState({stringifiedJson: e.message});
        }
      },
      render: function() {
        return (
          <div>
            <header>
              <textarea id="json_box" ref="textArea" value={this.state.textValue} onChange={this.onChange} placeholder="ここにJSONをいれてください"/>
            </header>
            <div id="content">
              <pre id="stringified_json">{this.state.stringifiedJson}</pre>
            </div>
          </div>
        );
      },
    });
    React.render(<App />, document.body);
  </script>
</html>