Implementing Socket.io with ReactJS ES6 Implementing Socket.io with ReactJS ES6 reactjs reactjs

Implementing Socket.io with ReactJS ES6


There are likely other solutions, but the following works for me:

1) npm install the socket client side package

2) import socket into the most root component of all components that need socket functionality

3) hookup server side socket event listeners in one of the lifecycle events (constructor / componentWillMount, componentDidMount)

4) pass down socket object through props if it makes sense to handle certain server events in child components

example:

import io from 'socket.io-client'let socket = io(`http://localhost:8000`)class App extends Component {  state = { data: {} }  componentDidMount() {        socket.on(`server:event`, data => {      this.setState({ data })    })  }  sendMessage = message => {    socket.emit(`client:sendMessage`, message)  }  render () {    return (      <Child         socket = { socket }         sendMessage = { this.sendMessage }      />    )  }}


You can instantiate a socket outside of the component and use it inside the component. Like this:

import React, { Component } from 'react'  import io from 'socket.io-client'var socket = io()class MyComponent extends Component {    componentDidMount() {        // You can use the socket inside the componet        socket.on('message', msg => console.log(msg))    }}


I had the same weird problem with socket.io and React. I wanted to determine a clear line of dependency injection with props to other components from my main.jsx file. Turned out that I only had to initialize io like this...

const socket = window.io();

And that was it. It worked.