Using websockets (ActionCable) with Rails app: Part 2 (React frontend)

Jimmy Cheung
Oct 19, 2020

--

In my first article, I covered the basics of setting up Rails to use ActionCable. Now, you can use ActionCable with a React frontend as well.

What you need

React

Rails

React ActionCable Provider

Instructions

  1. Set up the ActionCable as described in the previous article.
  2. Install react-actioncable-provider using the following commands
npm install --save @thrash-industries/react-actioncable-provider

3. In your React frontend, wrap the <App /> component in the ActionCable Provider code:

import { ActionCableProvider } from 'react-actioncable-provider';


<ActionCableProvider url='ws://localhost:3001/cable'>
<App />
</ActionCableProvider>

4. In the component itself where you wish to receive ActionCable subscriptions, wrap the component in the Action Cable Consumer code:

import { ActionCableConsumer } from 'react-actioncable-provider';

<ActionCableConsumer
channel={{ channel: '' }}
onReceived={}
/>

For the channel name, use the channel that you wish to subscribe to. The onReceived property can be used with a function that you run on the data that is received from the ActionCable channel.

Conclusion

Integrating React with ActionCable is relatively simple. Now, you can broadcast from your Rails app (using the instructions in the previous article), and then receive it in your React component to render.

Sources

https://github.com/ihollander/actioncable-starter-app

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet