import React, { Component } from 'react'; import { w3cwebsocket as W3CWebSocket } from "websocket"; import {Button, TextField, Grid, Container, Card, CardHeader, Paper, Avatar, FormHelperText} from "@mui/material"; export default class Chat extends Component { constructor(props) { super(props); } state = { messages: [], value:'', }; client = new W3CWebSocket('ws://' + window.location.host + '/ws/chat/' + this.props.orderId + '/'); componentDidMount() { this.client.onopen = () => { console.log('WebSocket Client Connected') } this.client.onmessage = (message) => { const dataFromServer = JSON.parse(message.data); console.log('Got reply!', dataFromServer.type); if (dataFromServer){ this.setState((state) => ({ messages: [...state.messages, { msg: dataFromServer.message, userNick: dataFromServer.user_nick, }], }) ) } } } componentDidUpdate() { this.scrollToBottom(); } scrollToBottom = () => { this.messagesEnd.scrollIntoView({ behavior: "smooth" }); } onButtonClicked = (e) => { if(this.state.value!=''){ this.client.send(JSON.stringify({ type: "message", message: this.state.value, nick: this.props.ur_nick, })); this.state.value = '' } e.preventDefault(); } render() { return ( {this.state.messages.map(message => <> {/* If message sender is not our nick, gray color, if it is our nick, green color */} {message.userNick == this.props.ur_nick ? } style={{backgroundColor: '#e8ffe6'}} title={message.userNick} subheader={message.msg} subheaderTypographyProps={{sx: {wordWrap: "break-word", width: 200}}} /> : } style={{backgroundColor: '#fcfcfc'}} title={message.userNick} subheader={message.msg} subheaderTypographyProps={{sx: {wordWrap: "break-word", width: 200}}} />} )}
{ this.messagesEnd = el; }}>
{ this.setState({ value: e.target.value }); this.value = this.state.value; }} />
The chat has no memory: if you leave, messages are lost. Learn easy PGP encryption.
) } }