Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 347
jacob blankenship Avatar asked Mar 06 '23 05:03

jacob blankenship


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();
}
like image 164
T.J. Crowder Avatar answered Mar 09 '23 00:03

T.J. Crowder