Preventing Page Scroll While New Data is Loading

I am currently working on a React class component that uses Post components. Within this component, there is a button that triggers the loading of more data from the database. The issue I am encountering is that when new data is fetched, the page automatically scrolls to the bottom. I would like to modify this behavior so that the user remains at their current position within the post feed.

Here is the code for my component:

import React,{Component} from 'react';
import Ride from '../Components/Ride';
import firebase from 'firebase'

class RideList extends Component{

    state={
        rides: [{
            user:{
                photo: '',
                name: '',
                uid: ''
            },
            likes: 0,
            likers: [],
            time: '',
            line: [{lng:22.01,lat:41.01}],
            when: 0
        }],
        lastDoc: {}
    }

    componentDidMount(){
            const db = firebase.firestore();
            db.collection('posts').orderBy('when','desc').limit(5).get().then(res=>{
                const data = []
                res.docs.map(doc=>{
                    data.push({...doc.data(),id: doc.id})
                })
                this.setState({rides: data, lastDoc: res.docs[res.docs.length-1]})
            }).catch(er=>{
                console.log(er)
            })
    }

    loadMore = ()=>{
        const rides = [...this.state.rides];
        const db = firebase.firestore();
        db.collection('posts').orderBy('when','desc').startAfter(this.state.lastDoc).limit(5).get().then(res=>{
                res.docs.map(doc=>{
                    rides.push({...doc.data(),id: doc.id})
                })
                this.setState({rides: rides, lastDoc: res.docs[res.docs.length-1]})
        })
    }

    render(){
        return(
            <div style={{textAlign:'start'}}>
                {this.state.rides.map((el,index)=>{
                        return(
                            <div>
                                <Ride key={el.when} {...el} user={this.props.user}/>
                            </div>
                        )
                })}
                {this.props.uid ? '':<button onClick={()=>this.loadMore()}>Load more</button>}
            </div>
        )
    }
}

export default RideList;

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

Error: Cannot read property 'X' of undefined in JavaScript when using Django framework

Using p5.js, I am creating drawings with data from a JSON provided by my Django backend. The draw function is defined at the base level of my HTML document within the script element: function draw(json) { if (json["leaf_text"]) { stroke(100) el ...

What is the best way to transform an array of objects into a nested array through shuffling

I am dealing with a diverse array of objects, each structured in a specific way: data = [ { content: { ..., depth: 1 }, subContent: [] }, { content: { ..., depth: 2 ...

Tips for avoiding re-rendering during onclick event handling

let content=useRef(); let toHide=useRef(); useEffect(()=>{ content.current=document.querySelectorAll('.content'); toHide.current=document.querySelectorAll('.hide'); toHide.current?.[0].addEventListener("cli ...

There seems to be an issue with AJAX form submission and it is not functioning properly

Having trouble submitting a form to another page using ajax, as it is not sending the post request. I have included Javascript at the top of the page: <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(function(){ ...

SyntaxError: An unidentified item was encountered at the <head> location

I have encountered an issue while loading a PHP file that utilizes ajax. Initially, the page loads without any errors. However, upon triggering the onclick event on a button, I receive the error message "Uncaught SyntaxError: Unexpected identifier" pointin ...

Change the value of a single element in an array using a component in ReactJS

I'm attempting to pass an array value to a specific index in one component and then assign a desired value from the child component. I need it to work this way because I'm developing a survey app where the number of questions can vary. This is j ...

Enhance your React/Bootstrap project with a hover effect class similar to Tailwind CSS's :hover feature

Is there a way to achieve the hover effect in React using Bootstrap similar to Tailwind's approach? I've searched online but haven't found any solutions. Appreciate any help! ...

Error in NextJs: The text content does not align with the server-rendered content

I am working on a new project using "NextJs", "date-fns", and "React-Calendar". However, I am facing an issue with date rendering between the server side (nodejs =english format) and client side (french): Warning: Text content did not match. Server: "April ...

What methods can be used to center a Google map on a specific location?

I am facing an issue with three map canvases on different divs. Despite setting the center to the same position in all three of them using JavaScript, the second and third maps do not seem to reflect that center. Does anyone have any insights on what cou ...

Creating a delay in a test to ensure a 5-second wait before validating the appearance of an element using React testing library

I am currently facing an issue in my React component where an element is supposed to appear after a delay of 5 seconds. I have been trying to write a test using 'jest fake timers' to check if the element appears after the specified time, but hav ...

In what situations is it essential to utilize the `rerender` function in the React Testing Library?

In the past, my team and I usually focused on writing React Testing Library (RTL) tests for the main parent components that contained numerous nested child components. This approach made sense and proved to be effective. The child components in question we ...

Discovering the total number of tickets based on priority in an array with Javascript

I have the following data set { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"Medium", task_id:T1 } { agent_id:002, priority:"High", task_id:T1 ...

Issue with React Project/NEXTJS: 404 Page Not Found

I'm facing an issue while trying to launch a React project utilizing Nextjs. Upon running "yarn run dev," the project fails to load in the browser and the console displays the following errors: GET http://localhost:3000/_next/static/chunks/webpack.js? ...

The information retrieved from an API fails to populate the table on the NextJS platform

I am facing an issue while trying to populate a table using an API call in NextJS. I have used the getStaticProps function to retrieve the data and pass it to the component. However, when I attempted to use the map() function to iterate over the data objec ...

Tips for applying/styling "All Items Center" and "Space Between Items" in CSS and ReactJS

justify-content: space-evenly; seems to be working correctly, but the desired output is not achieved I am aiming for something like this: https://i.stack.imgur.com/iQoWK.png However, this is what I currently have: https://i.stack.imgur.com/1PxGR.png ...

Focus event in IE does not always work as expected after an ajax request is

Our current focus is on supporting IE8 exclusively. An ajax call retrieves data from the server, replaces the HTML in a container div with the response, and then attempts to focus on an element within the response. However, there seems to be inconsistenci ...

Using WHERE clause effectively in an UPDATE statement in Node.js

Today, I have encountered an issue with my code that I would like to address. The problem lies in the PUT method where it currently updates all rows in the table instead of just the matched rows. How can I ensure that only the matched rows are updated? ...

Top method for creating integration tests in React using Redux and Enzyme

Currently, I am working on setting up integration tests within my application. There are a few API calls that occur both when the component mounts and upon a button click. The response from these API calls is stored in the app's store, which then upd ...

tips for remaining in modal window post form submission

I have a form within a modal window. I am using ajax to load content in the same modal window, but the issue is that it redirects to the main page after submitting the form. How can I ensure that the modal window stays open even after the form submission? ...

Show search results in real-time as you type

I am currently developing a SharePoint 2007 web part using Visual Studio. The main goal of this web part is to search a SharePoint list and present the results to the user. My objective is to have the results displayed automatically once the user finishes ...