Skip to content

Instantly share code, notes, and snippets.

@aditodkar
Created October 27, 2018 19:13
Show Gist options
  • Save aditodkar/7d9e1ecc45c7a22fa0529a275fe10094 to your computer and use it in GitHub Desktop.
Save aditodkar/7d9e1ecc45c7a22fa0529a275fe10094 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react'
import './chat.css'
import io from "socket.io-client";
export default class Chat extends Component {
constructor(props){
super(props);
this.state = {
message: '',
date: '',
messages: []
};
this.sendMessage = this.sendMessage.bind(this);
this.addMessage = this.addMessage.bind(this);
this.socket = io('localhost:5000');
}
componentDidMount() {
this.socket.on('RECEIVE_MESSAGE', data => {
this.addMessage(data);
this.setState({ messages: [...this.state.messages, data] })
});
}
sendMessage(event) {
event.preventDefault();
if(this.state.message !== ''){
this.socket.emit('SEND_MESSAGE', {
message: this.state.message,
date: Date.now()
});
//this.setState({ message: '', date: '' });
}
};
addMessage(data) {
//console.log(data);
this.setState({
messages: [...this.state.messages, data],
message: '',
date: ''
});
//console.log(this.state.message);
console.log(this.state.messages);
};
render() {
return (
<div>
<div id="status"></div>
<div id="chat">
<div className="card">
<div id="messages" className="card-block">
{this.state.messages.map((message, index) => {
return (
<div key={index} className="msgBox"><p className="msgText">{message.message}</p></div>
)
})}
</div>
</div>
<div className="row">
<div className="column">
<input id="inputmsg" type="text" placeholder="Enter Message...."
value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/>
</div>
<div className="column2">
<button id="send" className="button" onClick={this.sendMessage}>Send</button>
</div>
</div>
</div>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment