mardi 4 août 2015

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.


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire