Display the latest item using React

I've encountered a problem with displaying the last message in my pet chat application. Currently, I have to manually scroll to the bottom every time I open the chat in order to see the latest message. This scrolling behavior is not very user-friendly and I'm looking for a better solution.


'use client';

import '@styles/chat-messages.scss';
import ChatMessage from '@components/chat-message';
import Spinner from '@components/spinner';
import { LoadingContext } from '@components/providers/LoadingProvider';

import { useRef, useLayoutEffect, useState, useContext } from 'react';

export default function ChatMessages() {
    const [loading, setLoadingMessages] = useState(true);
    let messages = Array.from({ length: 10 }).reverse();

    const messagesEndRef = useRef<HTMLDivElement>(null);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
        
    };

    useLayoutEffect(() => {
        scrollToBottom();
        setLoadingMessages(false);
    }, [messages]);

    return (
        <div className='chat-messages'>
            {    
                !loading &&
                (                
                    messages.map((_, index) => (
                        <ChatMessage key={index} i={index} />
                ))
                )
            }
            {
                loading && (
                    <Spinner />
                )
            }
            <div ref={messagesEndRef} className='chat-messages__point'></div>
        </div>
    );
}

Currently, the chat starts from the top and then scrolls down as shown here: https://i.sstatic.net/QCgxG2nZ.png However, I would like it to display like this when opening the page: https://i.sstatic.net/Aned1h8J.png

If you'd like, you can sign in with Google (). The site uses simple oauth authentication. I've tried using the loading state but it hasn't resolved the issue. Is there a React hook that runs before the content is displayed?

Answer №1

Modify the action to automatic:

messagesEndRef.current?.scrollIntoView({ behavior: 'auto' }); 

Answer №2

One possible reason for this issue could be that the useLayoutEffect hook is being triggered before the messages are completely rendered, leading to the scrollToBottom function running prematurely. To resolve this, consider implementing the following code:

useEffect(() => {
    setLoadingMessages(false);
}, []);

useEffect(() => {
    if (!loading) {
        scrollToBottom();
    }
}, [loading, messages]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Events are not passed down to nested components in React

const App = () => { return ( <div> <div onClick={() => { console.log("Inner div"); }} > Inner div </div> </div> ); }; ReactDOM.render( <React.Fragment> ...

Require that JSX elements begin on a new line if the JSX element spans multiple lines

Which eslint rule favors the first syntax over the second when JSX code spans multiple lines? Currently, Prettier is changing `preferred` to `notPreferred`. const preferred = ( <tag prop={hi} another={test} \> ); const ...

Navigating from an AngularJS page to a ReactJS page on separate ports: A quick guide

I am currently working on an application with a landing page built using AngularJS. The login functionality is also AngularJS-based, and after a successful login, the user's token needs to be stored in local storage and then redirected to the landing ...

Problem with rendering React Router v4 ConnectedRouter on nested routes

The routes for the first level are correctly displayed from Layout.tsx, but when clicked on ResourcesUI.tsx, the content is not rendered as expected (see code below). The ResourceUI component consists of 2 sections. The left section contains links, and th ...

What steps do I need to take to create an animation where an outline gradually becomes filled in

I've been experimenting with creating a loading animation inspired by the pre-loading animation on this website. My attempt using chat GPT resulted in an unexpected outcome where, instead of filling the SVG, it placed a black square on top of it. The ...

Is there a way to simultaneously run both my Node application and React app with just one command?

I am planning to create a boilerplate for React and Node, with the following root folder structure: - (root level) - client - src - public - package.json - ... - package.json - server.js - node_module ...

Dynamic styling with jQuery input focus animation

Whenever I interact with the input field, I want my border colors to animate in and fade out smoothly. But I'm facing some challenges. Here is how I've set it up: HTML <input type="text" id="search-input" placeholder=&quo ...

Guiding the user to a different React page after a successful login: a simple solution

Currently, I am working on developing my very first full-stack application with React for front-end and Node.js with Express for back-end. I have set up a /login route using react router dom where users can input their email and password ...

Firefox does not display the line headings on the sides

Hey everyone, I'm facing a compatibility issue with CSS and Firefox today. When I go to my website www.fashoop.com, you'll notice some header lines on the sides. Here's an example in Google Chrome: (GOOGLE CHROME EXAMPLE) COLOR BLUE AN ...

The program encountered an issue: Initialization must be completed before utilizing hooks

I'm facing an issue with my new Next app. I added line no. 6 and now I'm getting an error. Can anyone help me understand why? https://i.sstatic.net/lMKH5.png import Head from "next/head"; import Image from "next/image"; impor ...

How to automatically disable a button in reactjs when the input field is blank

I have a component called Dynamic Form that includes input fields. The challenge I am facing is how to disable the submit button when these input fields are empty, although the validateResult function fails to return false. import cn from "classname ...

Ways to halt the expressjs server

After deploying my express and nextjs based app on EC2, I encountered an issue where the server automatically starts Nginx and node with different process IDs after I attempt to stop it by killing the process. This is happening even without using tools lik ...

Unable to integrate MUI components alongside Chakra UI

While working on my project with Chakra UI, I noticed that there isn't a datepicker component available. As a workaround, I tried using Material's datepicker but it only seems to work when I remove the ChakraProvider in index.js. import React fro ...

Can you describe the general structure of a favorite/star feature similar to Gmail's implementation?

Let me start by outlining the current tech stack we're utilizing, which includes AWS ELB EC2 instance with NodeJS, Restify, and other libraries for the backend, connected to DynamoDB. On the front-end, we have React with Redux. My goal is to implemen ...

Material-ui Select MenuItem not visible on screen

I'm having trouble with the Select MenuItem in Material-ui. After selecting an option, such as "Unit A", I am not seeing it displayed in my browser or console log. It appears to still be an empty string, and I can't figure out what I'm missi ...

Encountering a Next.js 404 Error while trying to access a dynamic route despite having the correct

I am experiencing a 404 error (This page could not be found.) when attempting to access a dynamic route in my current Next.js project. The specific URL is http://localhost:3000/blog/id, and I have already updated to the latest version of Next.js. Here is ...

When working with Typescript, an error may occur related to index types even though the constant object and its

I am struggling with understanding TypeScript, specifically when it comes to a problem I encountered. Hopefully, someone can shed some light on this for me. My issue revolves around a functional component that is responsible for displaying the correct com ...

Develop an asynchronous thunk that may lose its context if it is returned from different functions

Looking to consolidate 3 large thunks into one with parameters, I aim to create a createAsyncThunk function wrapper. Here's my approach: Code export const getExportThunk = <T>( handler: (args: T) => Promise<boolean>, route: string, ...

Error message occurs when MUI components return Uncaught TypeError

Hi there, I would really appreciate some help. I'm currently working on a react project using MUI and encountering an issue where certain components are not functioning correctly, resulting in an Uncaught TypeError error message. Could someone assist ...

Assign Equipment to Every Screen

Upon receiving this JSON response from an API in React Native, the data is stored as this.props.clothesList in Redux. The goal is to segregate objects with a `big_cloth_type` of 't' into the corresponding screen called TopScreen. Below is a snip ...