How to Build the Best Mobile Chat App with React Native

There’s no doubting it, Mobile technology is here to stay. If Pokemon Go couldn’t convince you, how about all of those other apps on your phone that you love so dearly? Today, we have some of the best mobile chat apps out there and they’re all right at your fingertips! We remember the days when mobile messaging was one of the biggest tech developments out there. Now, we’ve got iMessage, WhatsApp, LINE, Viber, and the list goes on. Did you ever think about how all of these messaging apps came to be? They all had to start somewhere. So, we’ve decided to go back to the basics. Learn how the best mobile chat app was built and of course, how to build to the best mobile chat app with React Native. Shall we begin?

Let’s Get Started

React Native is a JavaScript code library developed by Facebook and Instagram. It is the best mobile chat app when it comes to developers reusing codes across the web and on mobile platforms. Due to the different code bases of Android and iOS, startups and businesses often struggle to hire engineers for both. Therefore, with React Native, only one developer is needed to write across different mobile operating systems. In this tutorial, we will go just a little bit further than building a hello world app. Learn how to build a mobile chat app with React Native and Socket.IO.

Create A Chat App Project

How to Build the Best Mobile Chat App with React Native

Open the package.json in the chat app project and modify like so:

{
    "name": "ChatApp",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start"
    },
    "dependencies": {
        "react": "15.3.1",
        "react-native": "0.33.0",
        "socket.io-client": "1.4.8"
    }
}

Install All Necessary Packages

$ npm install
In order for this to be the best mobile chat app, we must install all necessary packages. First of all, we must create a user interface for our mobile chat app. For this app, we need a list view in order to display messages, text input and a button for input messages and sending functions. Go into the chat app directory, create a file named MainComponent.js with the code below: MainComponent.js
'use strict';
import React, {
    Component
} from 'react';
import {
    AppRegistry,
    StyleSheet,
    ListView,
    Text,
    TextInput,
    TouchableOpacity,
    View
} from 'react-native';
const ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2
});
var dataArray = [];
export default class MainComponent extends React.Component {
    constructor() {
        super();
        const ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2
        });
        this.state = {
            message: '',
            dataSource: ds.cloneWithRows(dataArray),
        };
    }
    render() {
        return ( < View style = { styles.container } > < ListView dataSource = { this.state.dataSource } enableEmptySections = { true } style = { styles.listMessage } renderRow = { (rowData) => < View style = { styles.message } > < Text > {
                    rowData
                } < /Text></View >
            }
            /> < View style = { styles.containerInput } > < TextInput style = { styles.inputMessage } onChangeText = { text => this.setState({
                message: text
            })
        }
        value = {
            this.state.message
        }
        /> < TouchableOpacity style = { styles.buttonSend } > < Text style = { { color: 'white', fontWeight: 'bold', } } > SEND < /Text></TouchableOpacity > < /View> < /View > );
}
}
const styles = StyleSheet.create({
    container: {
        marginTop: 20,
        flex: 1,
        flexDirection: 'column',
    },
    listMessage: {
        flex: 13,
        paddingLeft: 5,
        paddingRight: 5
    },
    message: {
        paddingTop: 5,
        paddingLeft: 5,
        paddingRight: 5
    },
    containerInput: {
        flex: 1,
        flexDirection: 'row',
    },
    inputMessage: {
        flex: 8,
        borderWidth: 1,
        borderColor: '#46b8da',
        padding: 10,
    },
    buttonSend: {
        flex: 2,
        borderWidth: 1,
        borderColor: '#46b8da',
        backgroundColor: '#5bc0de',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    }
});
In index.ios.js and index.android.js, we need to import the Main Component file from above. Open index.ios.js and index.android.js in your text editor and delete the current contents.

Add the following code below:

'use strict';
import React, {
    Component
} from 'react';
import {
    AppRegistry,
    StyleSheet,
    ListView,
    Text,
    TextInput,
    TouchableOpacity,
    View
} from 'react-native';
import MainComponent from './MainComponent.js';
class ChatApp extends Component {
    render() {
        return ( < MainComponent / > );
    }
};
AppRegistry.registerComponent('ChatApp', () => ChatApp);

On the terminal, run:

$ react-native run-ios
$ react-native run-android
How to Build the Best Mobile Chat App with React Native How to Build the Best Mobile Chat App with React Native Next, we need to create a socket server. In order to do this, please refer to the tutorial here. Follow it to run the server on port 8080. **Please Note: In app.js, change this line:
io.emit('onChat', msg);
to:
socket.broadcast.emit('onChat', msg);
You don’t want your message to appear twice. In our React Native chat app directory, create UserAgent.js and import it with socketio. If socket.io is required and executed before window.navigator.userAgent = “react-native” is called, the project will emit an error. UserAgent.js
window.navigator.userAgent = 'react-native';

Best Mobile Chat App Finish Line

Next, we need to modify our MainComponent.js like below:
'use strict';
import React, {
    Component
} from 'react';
import {
    AppRegistry,
    StyleSheet,
    ListView,
    Text,
    TextInput,
    TouchableOpacity,
    Platform,
    View
} from 'react-native';
import './UserAgent';
import io from 'socket.io-client/socket.io';
const ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2
});
var dataArray = [];
export default class MainComponent extends React.Component {
    constructor() {
        super();
        const ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2
        });
        this.state = {
            message: '',
            dataSource: ds.cloneWithRows(dataArray)
        };
        this.socket = io(Platform.OS === 'ios' ? 'http://localhost:8080' : 'http://10.0.2.2:8080', {
            jsonp: false
        });
        this.socket.on('onChat', data => {
            console.log(data);
            this.appendMessage(data, '#5cb85c');
        });
    }
    render() {
        return ( < View style = { styles.container } > < ListView dataSource = { this.state.dataSource } enableEmptySections = { true } style = { styles.listMessage } renderRow = { (rowData) => < View style = { styles.message } > < Text style = { { padding: 10, backgroundColor: rowData.color } } > {
                    rowData.message
                } < /Text></View >
            }
            /> < View style = { styles.containerInput } > < TextInput style = { styles.inputMessage } onChangeText = { text => this.setState({
                message: text
            })
        }
        value = {
            this.state.message
        }
        /> < TouchableOpacity style = { styles.buttonSend } onPress = { () => {
            this.emitMessage()
        }
    } > < Text style = { { color: 'white', fontWeight: 'bold', } } > SEND < /Text></TouchableOpacity > < /View> < /View > );
}
emitMessage() {
    this.socket.emit('onChat', this.state.message);
    this.appendMessage(this.state.message, '#f0ad4e');
    this.setState({
        message: '',
    });
}
appendMessage(message, color) {
    // color is for define user message color
    dataArray.push({
        message: message,
        color: color
    });
    this.setState({
        dataSource: ds.cloneWithRows(dataArray)
    });
}
}
const styles = StyleSheet.create({
    container: {
        marginTop: 20,
        flex: 1,
        flexDirection: 'column',
    },
    listMessage: {
        flex: 13,
        paddingLeft: 5,
        paddingRight: 5
    },
    message: {
        paddingTop: 5,
        paddingLeft: 5,
        paddingRight: 5
    },
    containerInput: {
        flex: 1,
        flexDirection: 'row',
    },
    inputMessage: {
        flex: 8,
        borderWidth: 1,
        borderColor: '#46b8da',
        padding: 10,
    },
    buttonSend: {
        flex: 2,
        borderWidth: 1,
        borderColor: '#46b8da',
        backgroundColor: '#5bc0de',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    }
});
Press cmd + R to reload for the iOS Simulator. Click double R to reload for Android emulator and there you have your react app! In conclusion, we hope this tutorial gave you more insight into how to create the best mobile chat app with React Native. Remember, mobile technology isn’t going anywhere and it’s one of the most in-demand tech skills out there. So, if you’re thinking about learning it, no better place to start than here! For more coding tutorials and info on the latest tech trends out there, be sure to visit our tech blog. How to Build the Best Mobile Chat App with React Native How to Build the Best Mobile Chat App with React Native
Share this article:
You may be interested in these articles