简体   繁体   中英

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

Context:

I am developing a Ruby On Rails application and I started using React.js to manage my javascript components. My application provides a facebook-like chat: several chats are displayed at the bottom of the page.

Problem

I have a ChatList component that renders the chats. A chat is made of its messages and its form. When this form is submitted, an AJAX call is made to the server to POST the message and the message is added to the current chat.

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

The server then broadcast Javascript code to the receiver.

This is where I'm stuck. How can I add the message to the correct chat? How can I select my React.js component and change its 'props'? When I was not using react, I used to broadcast this code to the other user:

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

I guess I have to find a way to select the React component (the chat instance) and change its property "messages". How?

Thank you for your help! :)

EDIT: I'm going to add more information, just in case:

  • My ChatList is a global variable that takes an array of Chats.
  • Each Chat takes an array of Message and a form.

When I submit the form of a chat, it adds the message to the Chat (locally and it also posts the new message to the server). When the server receives the POST event, it can render javascript code to the other user.

This code should add the message to the correct Chat for the correct user. There are two pieces missing:

  1. I don't know how I can "select" the Chat.
  2. I don't know how I can add a message to the "messages" array of this Chat.

You'll want to have your chat component listen to a WebSocket event for a new message and then call setState when a message is received.

The standard approach with Chatrooms is to use "channels" that each chat room subscribes to. That way it only hears about incoming messages from the conversation it cares about.

Check out Socket.io and its example on making a chat application. Even if you don't use Socket.io the example will be illustrative.

The 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();
    }
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM