Use socket.io with react native — Nov 2017

Abdul Haseeb
Nov 19, 2017 · 1 min read

I’d gone through many stack over flow questions regarding how to connect socket.io library with react native. Most of them are using some sort of complex method to get connect with sockets.

From some of the latest stack over flow questions, navigator.userAgent object is changed into react-native and then importing library, but this is very old and good method. I honestly couldn’t find a good article to connect socket.io with react-native.

The point of this article isn’t explain developing any react-native app with socket.io, but to demonstrate how to emit and listens to sockets in RN.

If you didn’t installed client side socket.io package on your RN app, you can easily done by running following command.

npm install --save socket.io-client

Now, go back to your app and import SocketIOClient

import SocketIOClient from ‘socket.io-client'

In your constructor, create an instance which will connect with your backend.

this.socket = SocketIOClient('http://localhost:80000');

Now, you’re automatically connected with your server. And you can start emitting to server & listens to data from server.

In the following example, Constructor will create an instance to socket of type SocketIOClient , and automatically connects with your server. When your app loads, socket emits a message ‘Hi server’ to your server through ‘channel1’.
When a user hit on ‘Click’ button, socket.io will emit an object to your server.

RN Code

Server Side:

Don’t forget to install dependencies and socket.io server library.

npm install --save socket.io

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store