How to use Socket.IO with React Native app.

Ahmed Ashraf
2 min readOct 18, 2016

I was facing a problem with my RN app, which is i wanna create a WebSocket connection using a socket.IO lib. after a little search, i have found this great article about the solution. which is you should change the userAgent obj to react-native. But when i did, this error appeared to me :

Iphone SE — IOS ( 10.0 )

So, and because of the navigator.userAgent is a read only object. I couldn’t assign react-native to it. So the solution is i had to use Object.defineProperty function to edit the userAgent object before importing the Socket.IO lib, So i changed my code to be :

if(Object.defineProperty){
Object.defineProperty(window.navigator, ‘userAgent’, {
configurable: true,
get: function(){
return “react-native”;
}})};

Then, i was able to use Socket.IO lib. easily with my RN app.

So after adding the socket.io-client lib.

npm i socket.io-client --save

i was able to import it in my code and start using it. And my final code was look like this :
PS: don’t forget to add jsonp: false option to your IO configure function.

‘use-strict’import React, { Component } from ‘react’;
import { … } from ‘react-native’;
// edit the userAgent object before importing the Socket.IO lib…
if(Object.defineProperty){
Object.defineProperty(window.navigator, ‘userAgent’, {
configurable: true,
get: function(){
return “react-native”;
}})}
// Import the Socket.IO lib.
import IO from ‘socket.io-client/socket.io’;
// My main component class…
module.exports = class MyComponent extends Component {
constructor(props){
super(props)
// define the IO connection…
this.socket = IO(this.props.baseURL, {query: … , jsonp: false})
// On connect…
this.socket.on(‘connect’, function(){
console.log(‘connected’);
})
}}

But the second problem i have faced was using JS-debugger feature on device. But you can pass this issue by disable it. and every thing should going right.

--

--