I'm pretty new to UI development, JavaScript, ReactJS, so please excuse lack of foundational knowledge.
I'm trying to develop a simple ReactJS application that accepts a User input through a Form, sends to a backend server and receives responses from the server. The backend server is listening on a WebSocket URL 'ws://localhost:8025/websockets/WSService'. I have provided the code snippet below. When I enter some text input and click on 'Submit' the message is successfully received by the server. I'm now trying to receive the response sent by the server and would like to know where to setup the 'onmessage' function.
I have reviewed the following questions already but they are slight variations to my requirement and I'm unable to map the suggestions directly to my solution:
- how react js acts as a websocket client?
- https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
Code snippet provided below:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
ws: new WebSocket('ws://localhost:8025/websockets/WSService'),
value: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
console.log(this.state.value);
}
handleSubmit(event) {
event.preventDefault();
this.state.ws.send(this.state.value);
console.log(event.target.value);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
react-websocketsays that you can render it as component.