<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ben Pong on Medium]]></title>
        <description><![CDATA[Stories by Ben Pong on Medium]]></description>
        <link>https://medium.com/@benpong89?source=rss-4e2f0aeb0110------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uhSJFjTPPcdjQpP9Ri5O2A.png</url>
            <title>Stories by Ben Pong on Medium</title>
            <link>https://medium.com/@benpong89?source=rss-4e2f0aeb0110------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 19:40:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benpong89/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Action Cable and React]]></title>
            <link>https://medium.com/@benpong89/action-cable-and-react-9a00be5e391b?source=rss-4e2f0aeb0110------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a00be5e391b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[actioncable]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Ben Pong]]></dc:creator>
            <pubDate>Sun, 11 Nov 2018 02:26:53 GMT</pubDate>
            <atom:updated>2019-03-12T00:53:37.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>Action Cable and React tutorial</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*SaW4-F0NsdFSf2C_pD4lTA.png" /></figure><p>Have you spent hours or days searching for a simple Rails Action Cable to React tutorial? Well, look no further!</p><p>This tutorial is for developers with a basic understanding of Rails and React. We’ll be using Rails, React and Webpack to create a real-time chat app. I’ll also briefly cover deploying to Heroku with Redis as well. <a href="https://actioncable-react-tutorial.herokuapp.com/">Live demo</a></p><p><strong>Section 1. Rails and Action Cable</strong></p><p>Let’s first create a Rails app.</p><pre>rails new actioncable_app<br>rails db:create</pre><p>Then, we’ll create a Model, Controller and Channel for our messages.</p><pre>rails g model Message body:string<br>rails g controller Messages<br>rails g channel Chat<br>rails db:migrate</pre><p>Next, go to your <em>chat.coffee </em>file and comment out everything here. What I discovered the hard way, is that when using React with Action Cable, you don’t need any Rails default CoffeeScript. We can use Action Cable with our own JS code.</p><p>Now to set up Action Cable, go to <em>chat_channel.rb.</em></p><p>In this file, we are going to create a stream within our ChatChannel. In this stream, clients and server will send and receive data. This stream is the WebSocket line of communication between clients and server. This is how we transmit data without the traditional HTML or AJAX request and response.</p><p>After we create a stream, we’ll define a method called speak. This method will receive data, manipulate that data to create a new instance of a Message, and then broadcast that new message into the stream. See below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d0a976fc34384d2d5cc56a593746b51/href">https://medium.com/media/9d0a976fc34384d2d5cc56a593746b51/href</a></iframe><p>Notice that I created a hash variable called socket instead of just broadcasting the message body directly. This is because Action Cable only allows you to broadcast objects. Broadcasting a string will throw an error.</p><p>Next, create a root html file to render our React components. Inside app/views/messages. Create a <em>root.html.erb</em> file and add this one line of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a23ae35eaaafca94032ead6abc0fc4d/href">https://medium.com/media/3a23ae35eaaafca94032ead6abc0fc4d/href</a></iframe><p>Go to <em>routes.rb </em>and add a couple of lines to your code as shown below. Notice we don’t need any HTML routes since we are using WebSocket instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10ada6df94b9312a10bc1b0639c12cc5/href">https://medium.com/media/10ada6df94b9312a10bc1b0639c12cc5/href</a></iframe><p>Let’s pause at this point. Start your Rails server and check that your local host page renders the <em>root.html.erb</em> file.</p><p>Next, we’ll configure our Webpack and create React components.</p><p><strong>Section 2. React and Webpack</strong></p><p>We’re going to use NPM to install React and Webpack. If you don’t already have NPM, install it <a href="https://www.npmjs.com/get-npm">here</a>. Then run the following lines of code.</p><pre>npm init<br>npm install webpack webpack-cli react react-dom @babel/core @babel/preset-react @babel/preset-env babel-loader</pre><p>Webpack bundles our JS files, gives us helpful errors and Babel transpiles JSX to JS and translates JS to &lt;ES6. There are a few ways to bundle JS files, but Webpack gets the job done.</p><p>To stay organized, create a frontend folder in the root of your Rails app. We’ll keep all of our React files here.</p><pre>|- actioncable_app<br>    |- frontend<br>        |- ChatRoom.js<br>        |- index.js<br>        |- MessageForm.js</pre><p>We’ll create our <em>index.js</em> and render some text to start.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1219ca0398b9401a34ff710b8899e6ca/href">https://medium.com/media/1219ca0398b9401a34ff710b8899e6ca/href</a></iframe><p>Now before we get too deep into React, let’s configure our Webpack and make sure we render our <em>index.js</em> component. Create a <em>webpack.config.js</em> file in your root directory and include the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2513a9aa5678fdb94617df6d3de209a7/href">https://medium.com/media/2513a9aa5678fdb94617df6d3de209a7/href</a></iframe><p>Note that we save the <em>bundle.js</em> file inside the Rails app/assets/javascript folder. This is so that it will be included in Rails <em>application.js</em> tree.</p><p>Now let’s bundle our JS files with Webpack.</p><pre>webpack --mode=development --watch</pre><p>Your local host page should now render the <em>index.js</em> component. In addition, Webpack will watch changes you make to your JS files by updating the <em>bundle.js </em>file, or it’ll give you helpful error messages. Neat!</p><p>Note, you probably want to git ignore your <em>bundle.js</em>.</p><p><strong>Section 3. React and Action Cable</strong></p><p>Now to the good stuff. We’ll start with our main <em>ChatRoom.js</em> component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6249990eca87d96da10adb1443971a9/href">https://medium.com/media/d6249990eca87d96da10adb1443971a9/href</a></iframe><p>In our componentDidMount function, we call a new function from App.cable.subscription. Recall the <em>chat_channel.rb</em> file from Rails. This snippet here is essentially the client-side counterpart.</p><p>The App.cable.subscription.create function takes in at least 3 important arguments.</p><ol><li><strong>Channel:</strong> We create a subscription to the ChatChannel channel. Note that the client only has to invoke this function and create a subscription once. Until the client unsubscribes, this subscription to the ChatChannel will persist.</li><li><strong>Received: </strong>When the client is subscribed, they will be listening to the Channel’s stream for any new data. When data is transmitted into the stream via the broadcast method called in the back end, this received function will be invoked.</li><li><strong>Speak: </strong>This function sends data to the back end. Recall in our <em>chat_channel.rb</em> file, we also have a method named speak. While these are two distinct functions, calling speak on the frontend, in turn invokes speak on the back end through the App.cable’ s perform function.</li></ol><p>Let’s take a moment and recap a couple of things.</p><p>Where did App.cable come from?</p><p>Check out <em>cable.js</em> that was created by Rails. You’ll see this code below. This is where App.cable was defined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bdaf0c67b7df32c4f45a12406a981d4/href">https://medium.com/media/8bdaf0c67b7df32c4f45a12406a981d4/href</a></iframe><p>Local state or Redux store?</p><p>If you’re creating a full-stack app you’ll probably want to use the Redux store. For example, when data is received on the client-side, instead of setting local state, you could dispatch a Redux action to update the store. In addition, you may even want to separate out the App.cable.subscription.create function call into its own component.</p><p>Almost done. Now we’ll create a <em>MessageForm.js</em> component to handle the submission of new messages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b313072fc81bccbdd0e417fad76dfb0/href">https://medium.com/media/8b313072fc81bccbdd0e417fad76dfb0/href</a></iframe><p>Notice in our handleSubmit function, we are invoking the speak function that we defined in the <em>ChatRoom.js</em> file. We key into our subscription, located at index [0] because we only have one, and then invoke speak. Why Action Cable creators made it so App.cable.subscriptions.subscriptions is the way to access all subscriptions, I don’t know. It looks janky but it works. Note that once again, we pass data through Action Cable as an object.</p><p>Lastly, let’s update our<em> index.js</em> component and add some template CSS.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8af2e89c7db8876f228ff8b152e77b3/href">https://medium.com/media/e8af2e89c7db8876f228ff8b152e77b3/href</a></iframe><p>Template CSS below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5c27081c3afea9231ef68b69f12939c/href">https://medium.com/media/e5c27081c3afea9231ef68b69f12939c/href</a></iframe><p>Congrats! You’ve created an app with a WebSocket connection through Rails Action Cable and React! <a href="https://actioncable-react-tutorial.herokuapp.com/">Live demo</a></p><p>Note, how do you know your WebSockets are working? One easy way to test using Chrome, is to open up your app (local host works too) in a regular tab and an incognito tab. You should be able to send messages in realtime between your regular and incognito tabs.</p><p><strong>Section 4. Advanced Action Cable features(optional)</strong></p><p>We’re going to create another subscription function called load, that will query all of the messages and send that data through the WebSocket. We’ll also update our received function to parse the data type being transmitted from the back end.</p><p>Update <em>chat_channel.rb</em> to add new load method and socket types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4d12f1cabfdd9ce1660516bd83b847e/href">https://medium.com/media/d4d12f1cabfdd9ce1660516bd83b847e/href</a></iframe><p>Update <em>ChatRoom.js</em>. Add new functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e5a9cdb0b072734de3dac3302ce4786/href">https://medium.com/media/0e5a9cdb0b072734de3dac3302ce4786/href</a></iframe><p><strong>Section 5. Heroku and Redis</strong></p><p>To keep this within scope, I’ll assume that you’ve successfully deployed your app to Heroku, but the WebSocket just won’t work. Took me a few days on the first try. No sweat, just a few easy steps.</p><p>On your Heroku app overview page, include the Heroku Redis add-on. Heroku requires that you add credit card information for account verification, but you won’t have to pay anything.</p><p>Next go to your gem file and uncomment out the Redis Gem. Bundle install.</p><p>Lastly, go to <em>cable.yml</em> file. Update the production section url to look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc5af4187f72bbc18f37aab71f392924/href">https://medium.com/media/dc5af4187f72bbc18f37aab71f392924/href</a></iframe><p>Your Heroku app should now work with WebSocket features. That’s all folks! Thank you for reading and I hope this helped!</p><p>Special shout out to Editor-in-Chief <a href="https://medium.com/u/4ad8f0adde78">Andrew Gregory</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a00be5e391b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>