Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up React component to listen to socket.io

I want my React component to listen to events from socket.io. My code works if I have the HTML files include:

<script src="socket.io/socket.io.js"></script>

and then the component's constructor() has:

this.socket = io(); // eslint-disable-line no-undef

The HTML file retrieves the proper socket.io client code from my Express server, and everything's fine.

But this feels so cheesy. I hate to rely on the global window name space to find the io() function. What's the best practice for letting a React component connect through socket.io to the server? Thanks.

like image 284
richb-hanover Avatar asked Mar 24 '26 05:03

richb-hanover


2 Answers

If you're using a bundler like Webpack or Browserify, you can use socket.io-client.

For instance:

const io = require('socket.io-client');

class MyComponent extends React.Component {
  constructor(...args) {
    super(...args);
    this.socket = io();
  }
  ...
}
like image 114
robertklep Avatar answered Mar 25 '26 19:03

robertklep


I would create the socket on componentWillMount and setState on the desired event callback.

like image 39
martriay Avatar answered Mar 25 '26 19:03

martriay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!