2015-01-31
ReactJS

I want to learn about ReactJS, but my blog currently has an AngularJS bias. So I want to see if I can integrate both ReactJS and AngularJS into my blog, which will let me do some side-by-side comparisons of the two frameworks.

I obtained the React Starter Kit 0.12.2 from the Getting Started page. I copied the build/ files (react.js, JSXTransformer.js and so on) into my blog’s static/reactjs/ directory and modified my partials/header.html to include these resources.

The ReactJS Hello World Example

Now I can do ReactJS. The <div> and script below should display a periodically updating timer message like "React has been successfully running for .... seconds".


The code for the above is:

<div id="container" class="card bg-well p-1">
  <p>
    ReactJS is not working if you see this text.
  </p>
</div>

<script>
  var ExampleApplication = createReactClass({
    render: function() {
      var elapsed = Math.round(this.props.elapsed  / 100);
      var roundElapsed = elapsed / 10 + (elapsed % 10 ? '' : '.0' );
      var message =
        'React has been successfully running for ' + roundElapsed + ' seconds.';

      return ReactDOMFactories.p(null, message);
    }
  });

  var ExampleApplicationFactory = React.createFactory(ExampleApplication);

  var start = new Date().getTime();
  var container = document.getElementById('container');
  setInterval(function() {
    ReactDOM.render(
      ExampleApplicationFactory({elapsed: new Date().getTime() - start}),
      container
    );
  }, 50);
</script>

See if AngularJS still works

I’m hoping I haven’t broken any of my previous AngularJS work by adding in ReactJS. Let’s write the equivalent of the above in Angular.


The code for the above is:

<div class="card bg-well p-1" ng-controller="ControllerA">
  <p>
    AngularJS has been successfully running for {{ timeString }} seconds.
  </p>
</div>

<script>
  function ControllerA($scope, $interval) {
    var start = new Date().getTime();
    $interval(
      function () {
        var elapsed = (new Date().getTime() - start);
        var roundElapsed = Math.round(elapsed / 100);
        $scope.timeString = roundElapsed / 10 + (roundElapsed % 10 ? '' : '.0' );
      }, 50);
  }
  angular
    .module('BlogApp')
    .controller('ControllerA', ControllerA);
</script>