At the moment I'm trying to write a simple chat application using React and SockJS. The problem I'm having is that I can't find a way for the state of my React class to change when socket.onmessage
is triggered. Here's what I've written so far:
/** @jsx React.DOM */
class Chatbox extends React.Component {
constructor() {
this.state = { messages: [] };
}
addMessage(message) {
let messages = this.state.messages;
message = "<span className=\"chat-message\">" + message + "</span>";
messages.push(message);
this.setState({ messages: messages });
}
clearChatbox() {
this.setState({ messages: [] });
}
render() {
return (
<div class="chatbox">
{this.state.messages.join("<br />")}
</div>
);
}
}
If I missed any other mistakes, I'd appreciate it if you could let me know.
Edit: The main problem here isn't the bindings I missed (which was just a dumb mistake on my part), but making the messages received by SockJS usable by the component itself.
Update: Alt solves the issue well for my case. Where adding messages is handled by ChatboxActions when the socket connection receives a message:
import React from 'react';
import ChatboxActions from '../actions/ChatboxActions';
import ChatboxStore from '../stores/ChatboxStore';
import connectToStores from 'alt/utils/connectToStores';
@connectToStores
class ChatBox extends React.Component {
constructor() {
super();
}
static getStores() {
return [ChatboxStore];
}
static getPropsFromStores(props) {
return ChatboxStore.getState();
}
static clearChatbox() {
alt.recycle(ChatboxStore);
}
render() {
<div className="chatbox">
{this.props.messages}
</div>
}
}