Using websockets (ActionCable) with Rails app: Part 2 (React frontend)
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
Instructions
- Set up the ActionCable as described in the previous article.
- 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.