I am using Socket.io for chatting feature in my react-native project. My project is using react native navigation. But I have trouble things passing Socket.io socket to certain screens. I want to share the socket with the navigation( like a prop I think I'm not sure ). Currently I'm using Socket.io socketes on each certain screens individually. But this way has some troubles. The main trouble is that when someone sends me a message I need to know which page I'm on while the app is running. Does someone have any suggestions on how to do it? My target is to share the same socket with three pages. I googled, but couldn't find any suitable results.
- AppNavigation.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
// Chat.
import ChatScreen from '../screens/Chat/ChatScreen';
import VideoChatScreen from '../screens/Chat/VideoChatScreen;
const Stack = createStackNavigator();
function AppNavigator() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Chat" component={ChatScreen} options={{ headerShown: false, gestureEnabled: false }}/>
<Stack.Screen name="VideoChat" component={VideoChatScreen} options={{ headerShown: false, gestureEnabled: false }}/>
</Stack.Navigator>
</NavigationContainer>
);
}
export default AppNavigator;
- ChatScreen.js
import React, { Component } from 'react';
import {connect} from 'react-redux';
import SocketIOClient from 'socket.io-client'
class ChatScreen extends Component {
constructor() {
super()
this.state = {}
this.socketClient = null;
}
componentDidMount() {
this.socketClient = SocketIOClient(url);
this.socketClient.onAny((event, params) => {
this.onResponseOnSocket(event, params);
});
}
...
- VideoChatScreen.js
import React, { Component } from 'react';
import {connect} from 'react-redux';
class VideoChatScreen extends Component {
constructor() {
super()
this.state = {}
this.socketClient = null;
}
componentDidMount() {
this.socketClient = SocketIOClient(url);
this.socketClient.onAny((event, params) => {
this.onResponseOnSocket(event, params);
});
}
...