Answer the question
In order to leave comments, you need to log in
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>"))
}
});
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question