|
| 1 | +// npm packages |
| 2 | +import React from 'react'; |
| 3 | + |
| 4 | +export default class Chat extends React.Component { |
| 5 | + constructor(props) { |
| 6 | + super(props); |
| 7 | + |
| 8 | + this.state = { |
| 9 | + episode: props.episode, |
| 10 | + }; |
| 11 | + } |
| 12 | + |
| 13 | + componentWillReceiveProps(nextProps) { |
| 14 | + if (nextProps.episode && (!this.state.episode || nextProps.episode._id !== this.state.episode._id)) { |
| 15 | + this.setState({episode: nextProps.episode}, () => { |
| 16 | + this.connectToServer(); |
| 17 | + }); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + connectToServer() { |
| 22 | + const {episode} = this.state; |
| 23 | + |
| 24 | + // Create WebSocket connection. |
| 25 | + const url = `ws://localhost:3000${episode._id}`; |
| 26 | + this.socket = new WebSocket(url); |
| 27 | + |
| 28 | + // Connection opened |
| 29 | + // this.socket.addEventListener('open', event => { |
| 30 | + // this.socket.send('Hello Server!'); |
| 31 | + // }); |
| 32 | + |
| 33 | + // Listen for messages |
| 34 | + this.socket.addEventListener('message', event => { |
| 35 | + console.log('Message from server', event.data); |
| 36 | + }); |
| 37 | + } |
| 38 | + |
| 39 | + render() { |
| 40 | + return ( |
| 41 | + <div className="column" style={{width: 340, maxWidth: 340, display: 'flex', flexDirection: 'column'}}> |
| 42 | + <div className="is-flex" style={{flexGrow: 1}}> |
| 43 | + Chat history |
| 44 | + </div> |
| 45 | + <div className="is-flex"> |
| 46 | + <div className="field has-addons" style={{flexGrow: 1}}> |
| 47 | + <p className="control" style={{flexGrow: 1}}> |
| 48 | + <input className="input" type="text" placeholder="Send a message.." /> |
| 49 | + </p> |
| 50 | + <p className="control" style={{marginRight: 10}}> |
| 51 | + <a className="button is-info"> |
| 52 | + Send |
| 53 | + </a> |
| 54 | + </p> |
| 55 | + </div> |
| 56 | + </div> |
| 57 | + </div> |
| 58 | + ); |
| 59 | + } |
| 60 | +} |
0 commit comments