Skip to content Skip to sidebar Skip to footer

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: and then th

Solution 1:

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();
  }
  ...
}

Solution 2:

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


Solution 3:

Thanks for sharing. I used the componentWillMount method. I also added a connection detection:

componentWillMount() {
  const socket = io(uri)

  socket.on('update', (data) => {
    this.setState({ data, connected: true })
  });

  socket.on('disconnect', () => {
    this.setState({ connected: false })
  });

  socket.on('reconnect', () => {
    this.setState({ connected: true })
  });
}

Post a Comment for "Set Up React Component To Listen To Socket.io"