Sahil
Sahil

Reputation: 25

InfiniteScroll (react-infinite-scroll-component) leads to the bottom of the page when new data populates

I am using InfiniteScroll (react-infinite-scroll-component). This is in reverse order. But it leads to the bottom of the page whenever I load new data using my API. This is my code:

<div
     id="scrollableDiv"
     style={{
       flex: 1,
       overflow: "auto",
       display: "flex",
       flexDirection: "column-reverse",
     }}
   >
     <InfiniteScroll
       dataLength={messageGroups.length}
       onScroll={e => {
         e.preventDefault();
         const scrollHeight = e.target.scrollHeight;
         const varHeight = e.target.scrollTop - e.target.clientHeight;
         console.log("varHeight", varHeight);
         if (scrollHeight + varHeight < 1) {
           onFetchPreviousMessages();
         }
       }}
       style={{ display: "flex", flexDirection: "column-reverse" }} //To put endMessage and loader to the top.
       id="scrollableDiv"
       ref={scrollableDiv}
       scrollableTarget="scrollableDiv"
     />
     <div ref={messageRef} />
     {!messageGroups.length && composeType === "help" && (
       <ExplorerLargeInfoBlock
         icon={<FaLifeRing />}
         header="Help Request"
         message="Need help? Send us a message below and someone on the project team will get back to you shortly."
       />
     )}
     {messageGroups.map(renderMessageGroup)}
</div>

I referred some posts where the div was being used, but not sure how to access the div.current in my case.

onFetchPreviousMessages is simply calling data API to fetch new data

Upvotes: 0

Views: 988

Answers (1)

Rehan Shakir
Rehan Shakir

Reputation: 137

To access the div.current in your case, you can use the useRef hook to create a reference to the scrollableDiv. Then, you can access the current property to get the underlying DOM element and manipulate its scroll behavior.

import { useRef } from "react";

const scrollableDiv = useRef(null);

<InfiniteScroll
  dataLength={messageGroups.length}
  next={onFetchPreviousMessages} // Use 'next' prop instead of 'onScroll'
  hasMore={true} // Assuming you have more data to load
  inverse={true} // Set this to true for reverse order
  loader={<h4>Loading...</h4>} // Optional: You can add a loading indicator
  scrollableTarget={scrollableDiv.current} // Pass the DOM element as the scrollable target
>
  {/* Render your message items here */}
</InfiniteScroll>
 const onFetchPreviousMessages = async () => {
  // Fetch your data here and update the messageGroups state
  // For example: const newData = await fetchData();
  // setMessageGroups([...newData, ...messageGroups]);

  // After adding new data, scroll back to the top
  scrollableDiv.current.scrollTop = 0;
};```

Upvotes: 0

Related Questions