Last active
April 3, 2022 20:34
-
-
Save drpancake/3b249c467061092e9538 to your computer and use it in GitHub Desktop.
React Native chat app with websockets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great ! Thanks