N
N
Nikolai Pavlovich2014-11-03 17:43:45
React
Nikolai Pavlovich, 2014-11-03 17:43:45

How to make work with websocket (receiving messages) in react.js?

I'm doing a chat. I decided to make a front on the react. But I can't figure out how to change the state of the component from the outside.

// часть реактовского кода
var RoomsList = React.createClass({
  render: function() {
    var roomNodes = this.props.data.map(function (room) {
      return (
        <Room caption={room.caption}>
          {room.users}
        </Room>
      );
    });
    return (
      <div className="roomsList">
        { roomNodes }
      </div>
    );
  }
});

var RoomsBox = React.createClass({
  render: function() {
    return (
      <div className="roomsBox">
        <RoomsList data={this.props.data} />
      </div>
    );
  }
});
React.render(
  <RoomsBox data={data} />,
  document.getElementById('rooms1')
);

// Часть  работы с Websocket. Там много мусора, просто для примера.
if (window["WebSocket"]) {
        conn = new WebSocket("ws://{{$}}/ws");
        conn.onopen = function(evt) {
            user = getQueryVariable('user');
            if (user==undefined) {
                user = "ooo";
            }
            data = {Op: 'auth', Room: 'msk', User: user, Content: ''};
            conn.send(JSON.stringify(data));
        }
        conn.onclose = function(evt) {
            appendLog($("<div><b>Connection closed.</b></div>"))
        }
        conn.onmessage = function(evt) {
            data = JSON.parse(evt.data);
            if (data.Op == "msg") {
                appendLog($("<div/>").text(data.User+": "+data.Content))
            } else if (data.Op == "room") {
                rooms.append(data.Caption+" | ");
            }
        }
    } else {
        appendLog($("<div><b>Your browser does not support WebSockets.</b></div>"))
    }
    });

It is necessary that upon admission, the list of rooms (RoomsList) is updated.
I understand that it is necessary to access the socket from the inside, but I don’t understand how to put it all down. The jQuery paradigm doesn't give )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
iMrDron, 2016-05-21
@iMrDron

React + Redux

I
Itvanya, 2017-03-10
@Itvanya

Your solution is react + redux. When you click on the submit button on the form, you trigger a ws event that sends data to you and all users in the same namespace. Having received the data on the client, you simply dispatch them to the editor store, which automatically updates all the data relative to the list.
There are a lot of implementation examples on github:
https://github.com/abitlog/retube
https://github.com/raineroviir/react-redux-socketi...
https://github.com/OmarElGabry/chat.io

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question