how to add an event listener to a state in react native

Viewed 11441

I'm trying to scroll to the end of my FlatList when the state of messages changes. Currently I'm using this.refs.flatList.scrollToEnd(); after waiting a bit, which works OK. What I want to do is add an event listener to the messages state so that when the list is changed in any way it will scroll to the end of the list. I tried

componentDidMount(){
        this.state.messages.addEventListener('change', this._handleNewMessage);
}

but it doesn't work. Does anyone know a way I can achieve this?

1 Answers

This would be what the lifecycle method componentDidUpdate is for:

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated. ...

Naturally, you have to ensure that this.state.messages is only changed via setState—but that was already true, using componentDidUpdate doesn't change that.

componentDidUpdate() {
    this.refs.flatList.scrollToEnd();
}
Related