So I have a react app, I want to include a file for websockets (currently a class) but I want to be able to call things in App from it (when the WS provides messages). I’m looking for something like a react callback prop, but I don’t think using a component is necessary since this class will not render anything.
Whats the best way to implement this?
class App extends React.Component {
constructor() {
super()
this.ws = undefined;
}
sendMessage(data) {
console.log(data)
}
connect = () => {
this.ws = new Websocket();
};
render() {
return <div>
<button onClick={this.connect}>Connect</button>
</div>
}
}
let ws = new WebSocket("ws://localhost:8080/");
export default class Websocket {
componentDidMount() {
ws.addEventListener("message", this.getPosition);
}
componentWillUnmount() {
ws.removeEventListener("message", this.getPosition);
}
giveData = ({data}) => {
//here I want to send the data to sendMessage in App component
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>