Add message to chat component (response.js) via websockets

Context:

I am developing a Ruby On Rails application and I started using React.js to manipulate my javascript components. My app provides a chat similar to facebook: multiple chats are displayed at the bottom of the page.

Problem

I have a ChatList component that displays chats. Chat consists of messages and a form. When this form is submitted, an AJAX call is sent to the server to send the message, and the message is added to the current chat.

this.setState({messages: this.state.messages.concat([newMessage])});

      

The server then passes the Javascript code to the recipient.

This is where I am stuck. How do I add a message to the correct chat? How can I select my React.js component and change its "props"? When I didn't use react, I used to pass this code to another user:

$("#chat-<%= chat.id %>").append("<%= message.content" %>);

      

I suppose I need to find a way to select a React component (chat instance) and change its "message" properties. How?

Thanks for the help!:)

EDIT: I'm going to add some additional information just in case:

  • My ChatList is a global variable that accepts an array of chats.
  • Each chat takes an array of messages and a form.

When I submit the chat form it adds a message to the chat (locally and also sends a new message to the server). When the server receives a POST event, it can display JavaScript code to another user.

This code should add a message to the correct Chat for the correct user. Two parts are missing:

  • I don't know how I can "select" Chat.
  • I don't know how to add a message to the "messages" array of this chat.
+3


source to share


2 answers


Solution in my Chat class:



componentDidMount: function(){
      this.props.privateChannel.bind('message.new', this.receiveMessage);
  },
receiveMessage: function(message) {
    if(message.user.id == this.props.recipient.id){
      this.setState({messages: this.state.messages.concat([message])});
      this.startBlink();
    }
},

      

0


source


You want your chat component to listen for the WebSocket event for a new message and then call setState

when the message is received.

The standard approach with chats is to use the "channels" that each chat room joins. Thus, he only hears the incoming messages from the conversation he cares about.



Socket.io and its example will open when creating a chat application. Even if you are not using Socket.io, the example will be illustrative.

+1


source







All Articles