Automatic scroll to bottom of list (displays newest messages entered) using React/Material UI

Viewed 3116

I am currently designing a chat bot to send messages for sales queries, I am having trouble with making it automatically scroll to the bottom of the list. This happens instead: How it looks

Here is my code for the mapping of said messages:

<List className={classes.messageArea}>
                                        {chatHistory.map(item => {
                                            return (
                                                <ListItem key={item}>
                                                    <Grid container>
                                                        <Grid item xs={12}
                                                              className={item.sent ? classes.msgsUs : classes.msgsScotti}>
                                                            <ListItemText align={item.sent ? "right" : "left"}
                                                                          primary={item.text}/>
                                                        </Grid>
                                                        <Grid item xs={item.sent ? 11 : 12}>
                                                            <ListItemText align={item.sent ? "right" : "left"}
                                                                          secondary={moment(item.time).format('HH:mm')}/>
                                                        </Grid>
                                                    </Grid>
                                                </ListItem>
                                            )
                                        })}
                                    </List>

How do I get it to automatically scroll to bottom when new messages are sent through, tried various methods but not accomplishing anything. Thanks for taking the time to look at this.

1 Answers

I've made an example for you. The main thing you need to do is setup a dependency on the list state changing. When this happens you need to scroll the window. One way to do this is with the Element.scrollIntoView() function.

I have included the full example here: https://codesandbox.io/s/confident-microservice-vibw8?file=/src/App.js

The main piece is here, where we run the API function whenever the list changes:

useEffect(() => {
  if (scrollRef.current) {
    scrollRef.current.scrollIntoView({ behaviour: "smooth" });
  }
}, [list]);
Related