Skip to content

Instantly share code, notes, and snippets.

@jillesme
Created May 29, 2020 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jillesme/518181297e89938a1d439191b904dbb5 to your computer and use it in GitHub Desktop.
Save jillesme/518181297e89938a1d439191b904dbb5 to your computer and use it in GitHub Desktop.
import React, { Component } from "react";
import { render } from "react-dom";
const Message = ({ text, date }) => (
<div id="message" className="card">
<div className="cell large-4">{text}</div>
<div className="cell large-2 text-right">
<small>{date}</small>
</div>
</div>
);
class App extends Component {
state = {
newMessage: "",
messages: []
};
chatSocket = {};
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
const roomName = location.pathname.substr(1);
const socketPath = "ws://" + window.location.host + "/ws/" + roomName;
this.chatSocket = new WebSocket(socketPath);
this.chatSocket.onmessage = e => {
const data = JSON.parse(e.data);
const message = { text: data.message, date: data.utc_time };
message.date = moment(message.date)
.local()
.format("YYYY-MM-DD HH:mm:ss");
const updatedMessages = this.state.messages.concat([message]);
this.setState({ messages: updatedMessages });
};
this.chatSocket.onclose = e => {
console.error("Chat socket closed unexpectedly");
};
this.inputRef.current.focus();
}
handleChange(ev) {
this.setState({ newMessage: ev.target.value });
}
handleSubmit() {
this.chatSocket.send(
JSON.stringify({
message: this.state.newMessage
})
);
this.setState({ newMessage: "" });
this.inputRef.current.focus();
}
render() {
return (
<div>
{this.state.messages.map((message, i) => (
<Message key={i} text={message.text} date={message.date} />
))}
<textarea cols="100" onChange={ev => this.handleChange(ev)} />
<br />
<input
ref={this.inputRef}
onClick={() => this.handleSubmit()}
type="button"
className="button"
value="Send"
/>
</div>
);
}
}
const container = document.getElementById("app");
render(<App />, container);
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment