Skip to content

Instantly share code, notes, and snippets.

@drpancake
Last active April 3, 2022 20:34
Show Gist options
  • Save drpancake/3b249c467061092e9538 to your computer and use it in GitHub Desktop.
Save drpancake/3b249c467061092e9538 to your computer and use it in GitHub Desktop.
React Native chat app with websockets
'use strict';
var React = require('react-native');
var {
AppRegistry,
Text,
TextInput,
ScrollView,
View
} = React;
var App = React.createClass({
getInitialState: function() {
return {
messages: []
}
},
componentDidMount: function() {
this.ws = new WebSocket('ws://siphon-chat.herokuapp.com');
this.ws.onmessage = function(event) {
if (event.data != 'ping') {
this.setState({
messages: [event.data].concat(this.state.messages)
});
}
}.bind(this);
this.ws.onerror = function() {
console.log('WebSocket error: ', arguments);
};
},
componentWillUnmount: function() {
this.ws.close();
},
handleSubmit: function(event) {
console.log('Sending: ' + event.nativeEvent.text);
this.ws.send(event.nativeEvent.text);
this.refs.textInput.setNativeProps({text: ''});
},
render: function() {
return (
<View style={{paddingTop: 20}}>
<TextInput
ref='textInput'
autoCapitalize='none'
autoCorrect='false'
placeholder='Enter a chat message...'
returnKeyType='send'
style={{height: 40, borderColor: 'gray', borderWidth: 1, margin: 10}}
onSubmitEditing={this.handleSubmit.bind(this)}
/>
<ScrollView style={{height: 400}}>
{
this.state.messages.map(m => {
return <Text style={{margin: 10}}>{m}</Text>
})
}
</ScrollView>
</View>
);
}
});
AppRegistry.registerComponent('App', () => App);
@Michael-AYK
Copy link

Great ! Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment