React Native and Socket.io build a chat app real time with nodeJs and express

React native socket.io chat app nodeJs server mobile application hybrid app express realtime

In this post, we are going to learn how to build a React Native Chat App with React Native and Socket.io. Socket.io is a widely-used JavaScript library mostly used for real-time web applications. It enables real-time, two-way, and event-based communication between the client (browser) and the server. It is built from Node.js and JavaScript client library. Its most prominent features are reliability, automatic reconnection, multigroup room support, and detecting breakage in connection.

Node JS Backend Setup


Project Structure 

project name
    node_modules
    package.json 
    server.js // server code here 
    socketManage.js // socket code here

Installing Command

npm i -s express socket.io

 

  • Create a server.js file and write a code 
const express = require("express");

const app = express();

const server = require("http").createServer(app);

const io = require('socket.io')(server)

const socketManage = require('./socketManage')(io)

io.on('connection', socketManage );

server.listen(6868, () => console.log("server running on port:" + 6868));

 

  • After that create a socketManage.js and write a code 
module.exports = io => socket => {

console.log("Made socket connection", socket.id, );

socket.on("chat message", msg => {

console.log(msg);

io.emit("chat message", msg);

});

socket.on("disconnect", () => {

io.emit("user disconnected", socket.userId);

});

}
  • Save the above code and run it with the following command.
node server.js
nodemon server.js // for nodemon install commnd npm i -g nodemon

React Native Code


Project Folder Structure

android
ios
node_modules
src
    ChatRoom.js
    App.js
app.json
babel.config.js
index.js
metro.config.js
package-lock.json
package.json

 

  • Creating a New Project run this command

ngx react-native init <Project-name>

  • After then Open  index.js  under the Project folder and add this code.

 

import {AppRegistry} from 'react-native';

import App from './src/App';

import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

 

  • After then src folder under the project folder like "project-name/src/" and cut the App.js of the root folder and paste src folder
  • After that add this code in App.js
import React from 'react';

import {

StyleSheet

} from 'react-native';

import SocketIOClient from 'socket.io-client';

import ChatRoom from './ChatRoom.js';

export default class App extends React.Component {

constructor(props) {

super(props);

this.state = {

messages: [],

name: "",

room: "",

isValid: false,

}

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

this.socket.on('connect', () => console.log('connected'));

this.socket.on('disconnect', () => console.log('disconnected'));

}

render() {

return (

<ChatRoom

name={this.state.name}

room={this.state.room}

socket={this.socket}

/>

);

}

}

const styles = StyleSheet.create({

mainContainer: {

flex: 1,

justifyContent: 'center',

alignItems: 'center',

},

form: {

width: '70%',

height: '40%',

justifyContent: 'center',

alignItems: 'center',

borderRadius: 8,

backgroundColor: '#0f97e0'

},

inputText: {

marginVertical: 10,

paddingHorizontal: 5,

paddingVertical: 3,

fontSize: 15,

width: '80%',

height: 30,

backgroundColor: '#fff',

borderRadius: 5,

},

submitBtn: {

marginTop: 25,

width: '60%',

height: 40,

justifyContent: 'center',

alignItems: 'center',

borderRadius: 5,

backgroundColor: '#c1c1c1'

},

btnText: {

fontSize: 20,

color: '#5b5b5b',

}

})
  • After then create ChatRoom.js under the src folder and add this code

import React from 'react';

import {

View,

Text,

StyleSheet,

TouchableOpacity,

FlatList,

SafeAreaView,

} from 'react-native';

export default class ChatRoom extends React.Component {

constructor(props) {

super(props);

this.state = {

messages: [],

}

this._onNewMsg();

}

_onNewMsg = () => {

this.props.socket.on('chat message', (message) => {

this.setState(prevState => ({

messages: [...prevState.messages, message]

}));

this._scrollToBottom(70);

}, () => {});

}

_sendMessage = () => {

this.props.socket.emit('chat message', {

room: 'Code',

from: 'codesolution',

text: 'Hello',

createdAt: new Date().now

}, () => {

this._scrollToBottom(50);

});

}

_renderName = (name) => {

return this.props.name !== name ? <Text style={{fontSize: 13, marginLeft: 5}}> {name} </Text> : null;

}

_scrollToBottom = (offset) => {

const scrollHeight = this.contentHeight - this.scrollViewHeight + offset;

if (scrollHeight > 0) {

this.flatlist.scrollToOffset({ offset: scrollHeight, animated: true });

}

}

render() {

return (

<SafeAreaView style={{flex: 1, marginTop: 20}}>

<FlatList

ref={flatlist => this.flatlist = flatlist}

data={this.state.messages}

keyExtractor={(item, index) => `${index}`}

onContentSizeChange={(w, h) => this.contentHeight = h}

onLayout={ev => this.scrollViewHeight = ev.nativeEvent.layout.height}

renderItem={({ item }) => {

const cellStyle = {

container: {

justifyContent: 'center',

alignItems: this.props.name === item.from ? 'flex-end' : 'flex-start',

},

textContainer: {

maxWidth: '70%',

marginHorizontal: 12,

marginVertical: 5,

paddingHorizontal: 13,

paddingVertical: 8,

backgroundColor: this.props.name === item.from ? '#2f73e0' : '#e2e2e2',

borderRadius: 10,

},

text: {

color: this.props.name === item.from ? '#ffffff' : '#282828',

fontSize: 15,

}

}

return (

<View style={cellStyle.container}>

{this._renderName(item.from)}

<View style={cellStyle.textContainer}>

<Text style={cellStyle.text}> {item.text} </Text>

</View>

</View>

);

}}

/>

<TouchableOpacity

style={styles.sendBtn}

onPress={() => this._sendMessage()}>

<Text style={{color: '#fff', fontSize: 18}}> Send Hello </Text>

</TouchableOpacity>

</SafeAreaView>

);

}

}

const styles = StyleSheet.create({

mainContainer: {

flex: 1,

justifyContent: 'center',

alignItems: 'center',

},

sendBtn: {

width: '100%',

height: 50,

justifyContent: 'center',

alignItems: 'center',

backgroundColor: '#2f73e0',

}

})

Run command

ngx react-native run-android
ngx react-native run-ios

Thank you


Github link: https://github.com/Sudarshan101/React-native-socket-chat-app.git
Youtube: https://www.youtube.com/watch?v=vZx6_7PUpTM

About the author
Code solution

info@codesolution.co.in

Discussion
  • 0 comments

Add comment To Login
Add comment