Monday, August 8, 2016

React.js - A guide for Rails developers_part 2


Nesting Components: Listing Records

For our first task, we need to render any existing record inside a table. First of all, we need to create an index action inside of our RecordsController:
  1.  # app/controllers/records_controller.rb
  2.   class RecordsController < ApplicationController
  3.     def index
  4.       @records = Record.all
  5.     end
  6.   end
Next, we need to create a new file index.html.erb under apps/views/records/, this file will act as a bridge between our Rails app and our react_component. To achieve this task, we will use the helper method react_component, which receives the name of the React component we want to render along with the data we want to pass into it.
  1.   <%# app/views/records/index.html.erb %>
  2.   <%= react_component 'Records', { data: @records } %>
It is worth mentioning this helper is provided by the react-rails gem, if you decide to use other React integration method, this helper will not be available.

You can now navigate to localhost:3000/records. Obviously, this won't work yet because of the lack of a Records React component, but if we take a look at the generated HTML inside the browser window, we can spot something like the following code
  1.   <div data-react-class="Records" data-react-props="{...}">
  2.   </div>
With this markup present, react_ujs will detect we are trying to render a React component and will instantiate it, including the properties we sent through react_component, in our case, the contents of @records.

The time has come for us to build our First React component, inside the javascripts/components directory, create a new file called records.js.coffee, this file will contain our Records component.
  1.   # app/assets/javascripts/components/records.js.coffee
  2.   @Records = React.createClass
  3.     render: ->
  4.       React.DOM.div
  5.         className: 'records'
  6.         React.DOM.h2
  7.           className: 'title'
  8.           'Records'
Each component requires a render method, which will be in charge of rendering the component itself. The render method should return an instance of ReactComponent, this way, when React executes a re-render, it will be performed in an optimal way (as React detects the existence of new nodes through building a virtual DOM in memory). In the snippet above we created an instance of h2, a built-in ReactComponent.

NOTE: Another way to instantiate ReactComponents inside the render method is through JSX syntax. The following snippet is equivalent to the previous one:
  1.   render: ->
  2.     `<div className="records">
  3.       <h2 className="title"> Records </h2>
  4.     </div>`
Personally, when I am working with CoffeeScript, I prefer using the React.DOM syntax over JSX because the code will arrange in a hierarchical structure by itself, similar to HAML. On the other hand, if you are trying to integrate React into an existing application built with erb, you have the option to reuse your existing erb code and convert it into JSX.

You can refresh your browser now.

Perfect! We have rendered our first React Component. Now, it's time to display our records.

Besides the render method, React components rely on the use of properties to communicate with other components and states to detect whether a re-render is required or not. We need to initialize our component's state and properties with the desired values:
  1.   # app/assets/javascripts/components/records.js.coffee
  2.   @Records = React.createClass
  3.     getInitialState: ->
  4.       records: @props.data
  5.     getDefaultProps: ->
  6.       records: []
  7.     render: ->
  8.       ...
The method getDefaultProps will initialize our component's properties in case we forget to send any data when instantiating it, and the getInitialState method will generate the initial state of our component. Now we need to actually display the records provided by our Rails view.

It looks like we are going to need a helper method to format amount strings, we can implement a simple string formatter and make it accesible to all of our coffee files. Create a new utils.js.coffee file under javascripts/ with the following contents:
  1.   # app/assets/javascripts/utils.js.coffee
  2.   @amountFormat = (amount) ->
  3.     '$ ' + Number(amount).toLocaleString()
We need to create a new Record component to display each individual record, create a new file record.js.coffee under the javascripts/components directory and insert the following contents:
  1.   # app/assets/javascripts/components/record.js.coffee
  2.   @Record = React.createClass
  3.     render: ->
  4.       React.DOM.tr null,
  5.         React.DOM.td null, @props.record.date
  6.         React.DOM.td null, @props.record.title
  7.         React.DOM.td null, amountFormat(@props.record.amount)
The Record component will display a table row containing table cells for each record attribute. Don't worry about those null in the React.DOM.* calls, it means we are not sending attributes to the components. Now update the render method inside the Records component with the following code:
  1. # app/assets/javascripts/components/records.js.coffee
  2.   @Records = React.createClass
  3.     ...
  4.     render: ->
  5.       React.DOM.div
  6.         className: 'records'
  7.         React.DOM.h2
  8.           className: 'title'
  9.           'Records'
  10.         React.DOM.table
  11.           className: 'table table-bordered'
  12.           React.DOM.thead null,
  13.             React.DOM.tr null,
  14.               React.DOM.th null, 'Date'
  15.               React.DOM.th null, 'Title'
  16.               React.DOM.th null, 'Amount'
  17.           React.DOM.tbody null,
  18.             for record in @state.records
  19.               React.createElement Record, key: record.id, record: record
Did you see what just happened? We created a table with a header row, and inside of the body table we are creating a Record element for each existing record. In other words, we are nesting built-in/custom React components. Pretty cool, huh?

When we handle dynamic children (in this case, records) we need to provide a key property to the dynamically generated elements so React won't have a hard time refreshing our UI, that's why we send key: record.id along with the actual record when creating Record elements. If we don't do so, we will receive a warning message in the browser's JS console (and probably some headaches in the near future).

You can take a look at the resulting code of this section here, or just the changes introduced by this section here.

Parent-Child communication: Creating Records

Now that we are displaying all the existing records, it would be nice to include a form to create new records, let's add this new feature to our React/Rails application.

First, we need to add the create method to our Rails controller (don't forget to use _strongparams):
  1.  # app/controllers/records_controller.rb
  2.   class RecordsController < ApplicationController
  3.     ...
  4.     def create
  5.       @record = Record.new(record_params)
  6.       if @record.save
  7.         render json: @record
  8.       else
  9.         render json: @record.errors, status: :unprocessable_entity
  10.       end
  11.     end
  12.     private
  13.       def record_params
  14.         params.require(:record).permit(:title, :amount, :date)
  15.       end
  16.   end
Next, we need to build a React component to handle the creation of new records. The component will have its own state to store date, title and amount. Create a new record_form.js.coffee file under javascripts/components with the following code:
  1.  # app/assets/javascripts/components/record_form.js.coffee
  2.   @RecordForm = React.createClass
  3.     getInitialState: ->
  4.       title: ''
  5.       date: ''
  6.       amount: ''
  7.     render: ->
  8.       React.DOM.form
  9.         className: 'form-inline'
  10.         React.DOM.div
  11.           className: 'form-group'
  12.           React.DOM.input
  13.             type: 'text'
  14.             className: 'form-control'
  15.             placeholder: 'Date'
  16.             name: 'date'
  17.             value: @state.date
  18.             onChange: @handleChange
  19.         React.DOM.div
  20.           className: 'form-group'
  21.           React.DOM.input
  22.             type: 'text'
  23.             className: 'form-control'
  24.             placeholder: 'Title'
  25.             name: 'title'
  26.             value: @state.title
  27.             onChange: @handleChange
  28.         React.DOM.div
  29.           className: 'form-group'
  30.           React.DOM.input
  31.             type: 'number'
  32.             className: 'form-control'
  33.             placeholder: 'Amount'
  34.             name: 'amount'
  35.             value: @state.amount
  36.             onChange: @handleChange
  37.         React.DOM.button
  38.           type: 'submit'
  39.           className: 'btn btn-primary'
  40.           disabled: !@valid()
  41.           'Create record'
Nothing too fancy, just a regular Bootstrap inline form. Notice how we are defining the value attribute to set the input's value and the onChange attribute to attach a handler method which will be called on every keystroke; the handleChange handler method will use the name attribute to detect which input triggered the event and update the related state value:
  1.   # app/assets/javascripts/components/record_form.js.coffee
  2.   @RecordForm = React.createClass
  3.     ...
  4.     handleChange: (e) ->
  5.       name = e.target.name
  6.       @setState "#{ name }": e.target.value
  7.     ...
We are just using string interpolation to dynamically define object keys, equivalent to @setState title: e.target.value when name equals title. But why do we have to use @setState? Why can't we just set the desired value of @state as we usually do in regular JS Objects? Because @setState will perform 2 actions, it:
  1. Updates the component's state
  2. Schedules a UI verification/refresh based on the new state
It is very important to have this information in mind every time we use state inside our components.

Lets take a look at the submit button, just at the very end of the render method:
  1.   # app/assets/javascripts/components/record_form.js.coffee
  2.   @RecordForm = React.createClass
  3.     ...
  4.     render: ->
  5.       ...
  6.       React.DOM.form
  7.         ...
  8.         React.DOM.button
  9.           type: 'submit'
  10.           className: 'btn btn-primary'
  11.           disabled: !@valid()
  12.           'Create record'
We defined a disabled attribute with the value of !@valid(), meaning that we are going to implement a valid method to evaluate if the data provided by the user is correct.
  1.   # app/assets/javascripts/components/record_form.js.coffee
  2.   @RecordForm = React.createClass
  3.     ...
  4.     valid: ->
  5.       @state.title && @state.date && @state.amount
  6.     ...
For the sake of simplicity we are only validating @state attributes against empty strings. This way, every time the state gets updated, the Create record button is enabled/disabled depending on the validity of the data.

Now that we have our controller and form in place, it's time to submit our new record to the server. We need to handle the form's submit event. To achieve this task, we need to add an onSubmit attribute to our form and a new handleSubmit method (the same way we handled onChange events before):
  1.   # app/assets/javascripts/components/record_form.js.coffee
  2.   @RecordForm = React.createClass
  3.     ...
  4.     handleSubmit: (e) ->
  5.       e.preventDefault()
  6.       $.post '', { record: @state }, (data) =>
  7.         @props.handleNewRecord data
  8.         @setState @getInitialState()
  9.       , 'JSON'
  10.     render: ->
  11.       React.DOM.form
  12.         className: 'form-inline'
  13.         onSubmit: @handleSubmit
  14.       ...
Let's review the new method line by line:
  1. Prevent the form's HTTP submit
  2. POST the new record information to the current URL
  3. Success callback
The success callback is the key of this process, after successfully creating the new record someone will be notified about this action and the state is restored to its initial value. Do you remember early in the post when I mentioned that components communicate with other components through properties (or @props)? Well, this is it. Our current component sends data back to the parent component through @props.handleNewRecord to notify it about the existence of a new record.

As you might have guessed, wherever we create our RecordForm element, we need to pass a handleNewRecord property with a method reference into it, something like React.createElement RecordForm, handleNewRecord: @addRecord. Well, the parent Records component is the "wherever", as it has a state with all of the existing records, we need to update its state with the newly created record.

Add the new addRecord method inside records.js.coffee and create the new RecordForm element, just after the h2 title (inside the render method).
  1.   # app/assets/javascripts/components/records.js.coffee
  2.   @Records = React.createClass
  3.     ...
  4.     addRecord: (record) ->
  5.       records = @state.records.slice()
  6.       records.push record
  7.       @setState records: records
  8.     render: ->
  9.       React.DOM.div
  10.         className: 'records'
  11.         React.DOM.h2
  12.           className: 'title'
  13.           'Records'
  14.         React.createElement RecordForm, handleNewRecord: @addRecord
  15.         React.DOM.hr null
  16.       ...
Refresh your browser, fill in the form with a new record, click Create record... No suspense this time, the record was added almost immediately and the form gets cleaned after submit, refresh again just to make sure the backend has stored the new data.

If you have used other JS frameworks along with Rails (for example, AngularJS) to build similar features, you might have run into problems because your POST requests don't include the CSRF token required by Rails, so, why didn't we run into this same issue? Easy, because we are using jQuery to interact with our backend, and Rails' jquery_ujs unobtrusive driver will include the CSRF token on every AJAX request for us. Cool!

You can take a look at the resulting code of this section here, or just the changes introduced by this section here.

Reusable Components: Amount Indicators

What would an application be without some (nice) indicators? Let's add some boxes at the top of our window with some useful information. We goal for this section is to show 3 values: Total credit amount, total debit amount and Balance. This looks like a job for 3 components, or maybe just one with properties?
We can build a new AmountBox component which will receive three properties: amount, text and type. Create a new file called amount_box.js.coffee under javascripts/components/ and paste the following code:
  1.   # app/assets/javascripts/components/amount_box.js.coffee
  2.   @AmountBox = React.createClass
  3.     render: ->
  4.       React.DOM.div
  5.         className: 'col-md-4'
  6.         React.DOM.div
  7.           className: "panel panel-#{ @props.type }"
  8.           React.DOM.div
  9.             className: 'panel-heading'
  10.             @props.text
  11.           React.DOM.div
  12.             className: 'panel-body'
  13.             amountFormat(@props.amount)
We are just using Bootstrap's panel element to display the information in a "blocky" way, and setting the color through the type property. We have also included a really simple amount formatter method called amountFormat which reads the amount property and displays it in currency format.

In order to have a complete solution, we need to create this element (3 times) inside of our main component, sending the required properties depending on the data we want to display. Let's build the calculator methods first, open the Records component and add the following methods:
  1.   # app/assets/javascripts/components/records.js.coffee
  2.   @Records = React.createClass
  3.     ...
  4.     credits: ->
  5.       credits = @state.records.filter (val) -> val.amount >= 0
  6.       credits.reduce ((prev, curr) ->
  7.         prev + parseFloat(curr.amount)
  8.       ), 0
  9.     debits: ->
  10.       debits = @state.records.filter (val) -> val.amount < 0
  11.       debits.reduce ((prev, curr) ->
  12.         prev + parseFloat(curr.amount)
  13.       ), 0
  14.     balance: ->
  15.       @debits() + @credits()
  16.     ...
credits sums all the records with an amount greater than 0, debits sums all the records with an amount lesser than 0 and balance is self-explanatory. Now that we have the calculator methods in place, we just need to create the AmountBox elements inside the render method (just above the RecordForm component):
  1.   # app/assets/javascripts/components/records.js.coffee
  2.   @Records = React.createClass
  3.     ...
  4.     render: ->
  5.       React.DOM.div
  6.         className: 'records'
  7.         React.DOM.h2
  8.           className: 'title'
  9.           'Records'
  10.         React.DOM.div
  11.           className: 'row'
  12.           React.createElement AmountBox, type: 'success', amount: @credits(), text: 'Credit'
  13.           React.createElement AmountBox, type: 'danger', amount: @debits(), text: 'Debit'
  14.           React.createElement AmountBox, type: 'info', amount: @balance(), text: 'Balance'
  15.         React.createElement RecordForm, handleNewRecord: @addRecord
  16.     ...
We are done with this feature! Refresh your browser, you should see three boxes displaying the amounts we've calculated earlier. But wait! There's more! Create a new record and see the magic work...

You can take a look at the resulting code of this section here, or just the changes introduced by this section here.
Written by Fernando Villalobos

If you found this post interesting, follow and support us.
Suggest for you:



Saturday, August 6, 2016

React.js - A guide for Rails developers_part 1


Introduction to React.js

React.js is the new popular guy around the "JavaScript Frameworks" block, and it shines for its simplicity. Where other frameworks implement a complete MVC framework, we could say React only implements the V (in fact, some people replace their framework's V with React). React applications are built over 2 main principles: Components and States. Components can be made of other smaller components, built-in or custom; the State drives what the guys at Facebook call one-way reactive data flow, meaning that our UI will react to every change of state.
One of the good things about React is that it doesn't require any additional dependencies, making it pluggable with virtually any other JS library. Taking advantage of this feature, we are going to include it into our Rails stack to build a frontend-powered application, or you might say, a Rails view on steroids.

A mock expense tracking app

For this guide, we are building a small application from scratch to keep track of our expenses; each record will consist of a date, a title and an amount. A record will be treated as Credit if its amount is greater than zero, otherwise it will be treated as Debit. Here is a mockup of the project:


Summarizing, the application will behave as follows:
  • When the user creates a new record through the horizontal form, it will be appended to the records table
  • The user will be able to inline-edit any existing record
  • Clicking on any Delete button will remove the associated record from the table
  • Adding, editing or removing an existing record will update the amount boxes at the top of the page
Initializing our React.js on Rails project

First things first, we need to start our brand new Rails project, we are naming it Accounts:
  1. rails new accounts
For this project's UI, we'll be using Twitter Bootstrap. The installation process is out of the scope of this post, but you can install the bootstrap-sass official gem following the instructions from the official github repo.
Once our project has been initialized, we proceed to include React. For this post I decided to include it via the official gem react-rails because we are going to take advantage of some cool features included in this gem, but there are other ways to achieve this task, like using Rails assets or even downloading the source package from the official page and pasting it into our javascripts folder.
If you have been developing Rails apps, you know how easy it is to install a gem: Add react-rails to your Gemfile.
  1.   gem 'react-rails', '~> 1.0'
Then, (kindly) tell Rails to install the new gems:
  1.   bundle install
react-rails comes with an installation script, which will create a components.js file and a components directory under app/assets/javascripts where our React components will live.
  1.  rails g react:install
If you take a look at your application.js file after running the installer, you will notice three new lines:
  1.  //= require react
  2.   //= require react_ujs
  3.   //= require components
Basically, it includes the actual react library, the components manifest file and a kind of familiar file ended in ujs. As you might have guessed for the file's name, react-rails includes an unobtrusive JavaScript driver which will help us to mount our React components and will also handle Turbolinks events.

Creating the Resource

We are going to build a Record resource, which will include a date, a title, and an amount. Instead of using the scaffold generator, we are going to use the resource generator, as we are not going to be using all of the files and methods created by the scaffold generator. Another option might be running the scaffold generator and then proceed to delete the unused files/methods, but our project can turn a little messy after this. Inside your project, run the following command:
  1.   rails g resource Record title date:date amount:float
After some magic, we will end up with a new Record model, controller, and routes. We just need to create our database and run pending migrations.
  1.  rake db:create db:migrate
As a plus, you can create a couple of records through rails console:
  1.  Record.create title: 'Record 1', date: Date.today, amount: 500
  2.   Record.create title: 'Record 2', date: Date.today, amount: -100
Don't forget to start your server with rails s.
Done! We're ready to write some code.

Nesting Components: Listing Records

For our first task, we need to render any existing record inside a table. First of all, we need to create an index action inside of our RecordsController:
  1.   # app/controllers/records_controller.rb
  2.   class RecordsController < ApplicationController
  3.     def index
  4.       @records = Record.all
  5.     end
  6.   end
Next, we need to create a new file index.html.erb under apps/views/records/, this file will act as a bridge between our Rails app and our React Components. To achieve this task, we will use the helper method react_component, which receives the name of the React component we want to render along with the data we want to pass into it.
  1.  <%# app/views/records/index.html.erb %>
  2.   <%= react_component 'Records', { data: @records } %>
It is worth mentioning this helper is provided by the react-rails gem, if you decide to use other React integration method, this helper will not be available.
You can now navigate to localhost:3000/records. Obviously, this won't work yet because of the lack of a Records React component, but if we take a look at the generated HTML inside the browser window, we can spot something like the following code
  1.   <div data-react-class="Records" data-react-props="{...}">
  2.   </div>
With this markup present, react_ujs will detect we are trying to render a React component and will instantiate it, including the properties we sent through react_component, in our case, the contents of @records.
The time has come for us to build our First React component, inside thejavascripts/components directory, create a new file called records.js.coffee, this file will contain our Records component.
  1.  # app/assets/javascripts/components/records.js.coffee

  2.   @Records = React.createClass
  3.     render: ->
  4.       React.DOM.div
  5.         className: 'records'
  6.         React.DOM.h2
  7.           className: 'title'
  8.           'Records'
Each component requires a render method, which will be in charge of rendering the component itself. The render method should return an instance of ReactComponent, this way, when React executes a re-render, it will be performed in an optimal way (as React detects the existence of new nodes through building a virtual DOM in memory). In the snippet above we created an instance of h2, a built-in ReactComponent.
NOTE: Another way to instantiate ReactComponents inside the render method is through JSX syntax. The following snippet is equivalent to the previous one:
  1.  render: ->
  2.     `<div className="records">
  3.       <h2 className="title"> Records </h2>
  4.     </div>`
Personally, when I am working with CoffeeScript, I prefer using the React.DOM syntax over JSX because the code will arrange in a hierarchical structure by itself, similar to HAML. On the other hand, if you are trying to integrate React into an existing application built with erb, you have the option to reuse your existing erb code and convert it into JSX.
You can refresh your browser now.
Written  by Fernando Villalobos

If you found this post interesting, follow and support us.
Suggest for you:

Build Web Apps with React JS and Flux

Meteor and React for Realtime Apps

Modern React with Redux

Build Apps with React Native

The Complete Web Development Tutorial Using React and Redux

Wednesday, August 3, 2016

Using JSX and React_part 2 (end)

We will also need some additional packages, and for that we will use bower.

Create a bower.json and add the following:

  1. {
  2.   "name": "react-webrtc-chat",
  3.   "main": "app.js",
  4.   "version": "0.0.0",
  5.   "ignore": [
  6.     "**/.*",
  7.     "node_modules",
  8.     "bower_components",
  9.     "public/lib",
  10.     "test",
  11.     "tests"
  12.   ],
  13.   "dependencies": {
  14.     "react": "~0.12.2",
  15.     "jquery": "~2.1.4",
  16.     "eventEmitter": "~4.2.7",
  17.     "peerjs": "~0.3.14",
  18.     "bootstrap": "~3.3.5"
  19.   }
  20. }

With this configuration, we bring down react, jQuery, bootstrap, eventEmitter for firing events and the peerJS Client library for wrapping the WebRTC.

Finally, specify where to install this by setting the .bowerrc file:

  1. {
  2.   "directory": "src/lib"
  3. }

From here, just sit back and install your dependencies via:


  1. $ bower install && npm install

Once this command has finished, you will see a new directory node_modules and src/lib. These contain the modules ready for use.

Now create an app.js in the main directory alongside your package.json, etc. This will be the main entry point of your application

  1. //Configure our Services
  2. var express = require('express'),
  3.     PeerServer = require('peer').PeerServer,
  4.     events = require('./src/Events.js'),
  5.     app = express(),
  6.     port = process.env.PORT || 3001;
  7.  
  8. //Tell express to use the 'src' directory
  9. app.use(express.static(__dirname + '/src'));
  10.  
  11. //Configure the http server and PeerJS Server
  12. var expressServer = app.listen(port);
  13. var io = require('socket.io').listen(expressServer);
  14. var peer = new PeerServer({ port: 9000, path: '/chat' });
  15.  
  16. //Print some console output
  17. console.log('#### -- Server Running -- ####');
  18. console.log('Listening on port', port);
  19.  
  20. peer.on('connection', function (id) {
  21.   io.emit(events.CONNECT, id);
  22.   console.log('# Connected', id);
  23. });
  24.  
  25. peer.on('disconnect', function (id) {
  26.   io.emit(events.DISCONNECT, id);
  27.   console.log('# Disconnected', id);
  28. });

This will simply create an Express server, making the src/ files we just got with bower now accessible via HTTP. Then a socket.io instance was created to listen on the expressServer object. This is used for polling and facilitating the next step for the PeerServer, which will actually do the WebRTC chat part.

To configure a PeerServer, all you need to do is specify the port and path the server will run on, and then start configuring events with the .on method. We are using a separate file named Events.js to specify our app’s events.

  1. peer.on('connection', function (id) {
  2.   io.emit(events.CONNECT, id);
  3.   console.log('# Connected', id);
  4. });

Here we use the events.CONNECT event to specify when a user has connected to our app. This will be used by the states of our view components to update their displays in real time.

To do this, we need to create the Server for our peer-to-peer connections to proxy through.

Create a file in src/Server.js and add the following:

  1. /* global EventEmitter, events, io, Peer */
  2. 'use strict';
  3.  
  4. function ChatServer() {
  5.   EventEmitter.call(this);
  6.   this._peers = {};
  7. }
  8.  
  9. ChatServer.prototype = Object.create(EventEmitter.prototype);
  10.  
  11. ChatServer.prototype.onMessage = function (cb) {
  12.   this.addListener(events.MSG, cb);
  13. };
  14.  
  15. ChatServer.prototype.getUsername = function () {
  16.   return this._username;
  17. };
  18.  
  19. ChatServer.prototype.setUsername = function (username) {
  20.   this._username = username;
  21. };
  22.  
  23. ChatServer.prototype.onUserConnected = function (cb) {
  24.   this.addListener(events.CONNECT, cb);
  25. };
  26.  
  27. ChatServer.prototype.onUserDisconnected = function (cb) {
  28.   this.addListener(events.DISCONNECT, cb);
  29. };
  30.  
  31. ChatServer.prototype.send = function (user, message) {
  32.   this._peers[user].send(message);
  33. };
  34.  
  35. ChatServer.prototype.broadcast = function (msg) {
  36.   for (var peer in this._peers) {
  37.     this.send(peer, msg);
  38.   }
  39. };
  40.  
  41. ChatServer.prototype.connect = function (username) {
  42.   var self = this;
  43.   this.setUsername(username);
  44.   this.socket = io();
  45.   this.socket.on('connect', function () {
  46.     self.socket.on(events.CONNECT, function (userId) {
  47.       if (userId === self.getUsername()) {
  48.         return;
  49.       }
  50.       self._connectTo(userId);
  51.       self.emit(events.CONNECT, userId);
  52.       console.log('User connected', userId);
  53.     });
  54.     self.socket.on(events.DISCONNECT, function (userId) {
  55.       if (userId === self.getUsername()) {
  56.         return;
  57.       }
  58.       self._disconnectFrom(userId);
  59.       self.emit(events.DISCONNECT, userId);
  60.       console.log('User disconnected', userId);
  61.     });
  62.   });
  63.   console.log('Connecting with username', username);
  64.   this.peer = new Peer(username, {
  65.     host: location.hostname,
  66.     port: 9000,
  67.     path: '/chat'
  68.   });
  69.   this.peer.on('open', function (userId) {
  70.     self.setUsername(userId);
  71.   });
  72.   this.peer.on('connection', function (conn) {
  73.     self._registerPeer(conn.peer, conn);
  74.     self.emit(events.CONNECT, conn.peer);
  75.   });
  76. };
  77.  
  78. ChatServer.prototype._connectTo = function (username) {
  79.   var conn = this.peer.connect(username);
  80.   conn.on('open', function () {
  81.     this._registerPeer(username, conn);
  82.   }.bind(this));
  83. };
  84.  
  85. ChatServer.prototype._registerPeer = function (username, conn) {
  86.   console.log('Registering', username);
  87.   this._peers[username] = conn;
  88.   conn.on('data', function (msg) {
  89.     console.log('Message received', msg);
  90.     this.emit(events.MSG, { content: msg, author: username });
  91.   }.bind(this));
  92. };
  93.  
  94. ChatServer.prototype._disconnectFrom = function (username) {
  95.   delete this._peers[username];
  96. };

This is the main guts of the application. Here we configure the ChatServer object with all of its functions.

First we use socket.io to establish signalling of a new user connected via the events.CONNECT as so:

  1. ChatServer.prototype.connect = function (username) {
  2.   var self = this;
  3.   this.setUsername(username);
  4.   this.socket = io();
  5.   this.socket.on('connect', function () {
  6.     self.socket.on(events.CONNECT, function (userId) {
  7.       if (userId === self.getUsername()) {
  8.         return;
  9.       }
  10.       self._connectTo(userId);
  11.       self.emit(events.CONNECT, userId);
  12.       console.log('User connected', userId);
  13.     });

Then, to connect to the PeerServer, we use the following:

  1. this.peer = new Peer(username, {
  2.     host: location.hostname,
  3.     port: 9000,
  4.     path: '/chat'
  5.   });

We then listen for events via the on method:this.peer.on('open', function (userId) {

  1.     self.setUsername(userId);
  2.  });
  3. this.peer.on('connection', function (conn) {
  4.     self._registerPeer(conn.peer, conn);
  5.     self.emit(events.CONNECT, conn.peer);
  6.  });

We also have our JSX inside components in the components/chat directory. Take your time to look through all of them in the repository. I will be focusing on the ChatBox component for now:

  1. /** @jsx React.DOM */
  2.  
  3. 'use strict';
  4.  
  5. var ChatBox = React.createClass({
  6.  
  7.   getInitialState: function () {
  8.     return { users: [] };
  9.   },
  10.  
  11.   componentDidMount: function () {
  12.     this.chatProxy = this.https://school.codequs.com/p/SkRTHvU_props.chatProxy;
  13.     this.chatProxy.connect(this.props.username);
  14.     this.chatProxy.onMessage(this.addMessage.bind(this));
  15.     this.chatProxy.onUserConnected(this.userConnected.bind(this));
  16.     this.chatProxy.onUserDisconnected(this.userDisconnected.bind(this));
  17.   },
  18.  
  19.   userConnected: function (user) {
  20.     var users = this.state.users;
  21.     users.push(user);
  22.     this.setState({
  23.       users: users
  24.     });
  25.   },
  26.  
  27.   userDisconnected: function (user) {
  28.     var users = this.state.users;
  29.     users.splice(users.indexOf(user), 1);
  30.     this.setState({
  31.       users: users
  32.     });
  33.   },
  34.  
  35.   messageHandler: function (message) {
  36.     message = this.refs.messageInput.getDOMNode().value;
  37.     this.addMessage({
  38.       content: message,
  39.       author : this.chatProxy.getUsername()
  40.     });
  41.     this.chatProxy.broadcast(message);
  42.   },
  43.  
  44.   addMessage: function (message) {
  45.     if (message) {
  46.       message.date = new Date();
  47.       this.refs.messagesList.addMessage(message);
  48.     }
  49.   },
  50.  
  51.   render: function () {
  52.     return (
  53.       <div className="chat-box" ref="root">
  54.         <div className="chat-header ui-widget-header">React p2p Web RTC Chat</div>
  55.         <div className="chat-content-wrapper row">
  56.           <UsersList users={this.state.users} username={this.props.username} ref="usersList"></UsersList>
  57.           <MessagesList ref="messagesList"></MessagesList>          
  58.         </div>
  59.         <MessageInput
  60.           ref="messageInput"
  61.           messageHandler={this.messageHandler}>
  62.         </MessageInput>
  63.       </div>
  64.     );
  65.   }
  66. });

This class takes usage of the ChatServer we created before, utilising it as a proxy for the ChatBox component.

The components and libraries are finally all rendered on the page with index.html and served via node express.

To start the app, run npm start and point your browser to http://localhost:3001 to take a look at the chat.

Going Live on Heroku
Serving from the cloud is really easy with Heroku. Sign up for a free account and then you can install the heroku toolbelt on to your system. Read more about getting Heroku set up at the Heroku Dev Center.

Now that you have Heroku available, log in and create a new project like so:

  1. $ git clone git@github.com:tomtom87/react-p2p-chat.git
  2. $ cd react-p2p-chat
  3. $ heroku create
  4. Creating sharp-rain-871... done, stack is cedar-14
  5. http://sharp-rain-871.herokuapp.com/ | https://git.heroku.com/sharp-rain-871.git
  6. Git remote heroku added

Here you will get a random name from Heroku and your app URL—in our example it is http://sharp-rain-871.herokuapp.com/. Heroku also creates a git repo for this app.

Now it’s as simple as pushing your code to heroku:

  1. $ git push heroku master

Once the push is finished, you will be able to start your web service with the following:

  1. $ heroku ps:scale web=1

Now just visit the URL provided, or as a shortcut use the open command as so:

  1. $ heroku open

Conclusions

You’ve learned how to create JSX components and interface them with React, with a detailed example of the chat application. Take some time to go through the code and see how React and the components/chat directory are working.

Combined with the deployment to Heroku, you can start hacking and creating your own React apps for the cloud!
Written by Tom Whitbread
If you found this post interesting, follow and support us.
Suggest for you:

Build Web Apps with React JS and Flux

Meteor and React for Realtime Apps

Modern React with Redux

Build Apps with React Native

The Complete Web Development Tutorial Using React and Redux