Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React + Redux: Scrolling a DOM element after state change

Tags:

reactjs

redux

New to Redux here, really just looking for a "best practice" answer.

I am building a chat application using React + Redux. My app looks something like this:

  • 3 stateless components for my app container, message list, and input bar
  • Actions for adding user messages/responses
  • A reducer that takes in these actions and returns a messages array
  • Chat middleware which handles a emitting a socket message when then ADD_MESSAGE action is dispatched

So far so good. Everything is working well, however I'm unsure of how/where in this sequence I should be making DOM manipulations. Specifically, I would like to scroll to the bottom of my message-list container whenever my messages state changes.

All I need to fire is something like: messagesListElement.scrollTop = messagesListElement.scrollHeight;, but not sure where the appropriate place to do this is.

like image 817
Nicholas Haley Avatar asked Nov 20 '16 18:11

Nicholas Haley


1 Answers

You mentioned that all the three components are stateless which means the messages are maintained in redux store which means they are passed as props to the child components. Basically there are five life cycle methods which could get triggered after/before the component gets updated.

  • componentWillReceiveProps()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • componentDidUpdate()
  • render()

Now since you want to scroll down after a new message is pushed to the messages state, the best place to do this would be componentDidUpdate()

Why not componentWillReceiveProps - This is the function which will get executed just before a new message is about to be passed in the new props of the component. This is the best place to update your component's state against the new props but since your component is stateless, this is not the right place for scrolling. This could be helpful

Hope it helps :)

like image 115
Swapnil Avatar answered Nov 13 '22 20:11

Swapnil