1

I am working on a chat app, everytime I put a message I need to scroll to the bottom in order to see the new messages. So, as in a regular chat, I need to provide the functionality that the user may be able to see the last messages without manually scrolling to the bottom.

I am using React, is there a css way? or can you tell me the best way to do that ?

let me show you some code

this is the main component

  render () {
    let messages = this.props.chatMessages.map((message) => {
      return <ChatItem info={message.info} me={message.me} player={message.player} message={message.message} />;
    });

    let chatForm;

    if (this.props.mode === 'player') {
      chatForm = <ChatForm onAddMessage={this.addMessage} />;
    }

    return <div className="Chat">
      <ul className="Chat__messages">{messages}</ul>
      <hr />
      <div>{chatForm}</div>
    </div>;
  }

here are the ChatItem and ChatForm components

  render () {
    let item;
    const { message, player, me, info } = this.props;

    if (info) {
      item = <li><em>{message}</em></li>;
    }
    else if (me) {
      item = <li><strong>Me: {message}</strong></li>;
    }
    else {
      item = <li><strong>{player}:</strong> {message}</li>;
    }

    return item;
  }


  render () {
    return <div className="ChatForm">
      <input
        className="ChatForm__input"
        placeholder="Your message..."
        ref="newMessage"
        onKeyDown={this.onKeyDown}
        autofocus="true" />
    </div>;
  }

ADDING INFO

I need something like this http://codepen.io/TimPietrusky/pen/ylkFs

Look at this part

  // Scroll the latest line of output
  output.scrollTop(
    output[0].scrollHeight - output.height()
  );

how should I adapt it to my code on React ?

Non
  • 8,409
  • 20
  • 71
  • 123
  • Take a look at this [jquery with react][1]. [1]: http://stackoverflow.com/questions/25436445/using-jquery-plugins-that-transform-the-dom-in-react-components – João Lima Aug 18 '15 at 00:59

1 Answers1

2

One way to do it is to compare current and previous/next props in a lifecycle event such as componentDidUpdate and scroll to bottom if a new message was added. For example:

componentDidUpdate(prevProps) {
  // Check if new message was added, for example:
  if (this.props.messages.length === prevProps.messages.length + 1) {
    // Scroll to bottom
  }
}
franky
  • 1,323
  • 1
  • 12
  • 13