Skip to content

Instantly share code, notes, and snippets.

@nxsyed
Last active June 7, 2018 20:18
Show Gist options
  • Save nxsyed/0f390ba5d3ea22040ef7dcb2ba73fd16 to your computer and use it in GitHub Desktop.
Save nxsyed/0f390ba5d3ea22040ef7dcb2ba73fd16 to your computer and use it in GitHub Desktop.
import React from 'react';
class Chat extends React.Component{
// return the initial state of our Chat class
constructor() {
super();
this.chat = new ChatClient.Chat(`${now}chat`);
this.state = {
messages: [],
chatInput: ''
};
}
// update the input field when the user types something
setChatInput = (event) => {
this.setState({ chatInput: event.target.value })
}
// send the message to the other users
sendChat = () => {
if (this.state.chatInput) {
ChatEngine.global.emit('message', {
text: this.state.chatInput
});
this.setState({ chatInput: '' })
}
}
// listen for a 'message' event and fire a callback
componentDidMount() {
ChatEngine.global.on('message', (payload) => {
let messages = this.state.messages;
messages.push(
<Message
key={ this.state.messages.length }
uuid={ payload.sender.uuid }
text={ payload.data.text } />
);
this.setState({
messages: messages
});
});
}
// bind the 'Enter' key for sending messages
_handleKeyPress(e) {
if (e.key === 'Enter') {
this.sendChat();
}
}
// render the input field and send button
render() {
return (
<div>
<div id="chat-output"> { this.state.messages } </div>
<input
id="chat-input"
type="text"
name=""
value={ this.state.chatInput }
onChange={ this.setChatInput }
onKeyPress={ this._handleKeyPress }/>
<input
type="button"
onClick={ this.sendChat }
value="Send Chat" / >
</div>
);
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment