Created
July 30, 2022 09:35
-
-
Save prosenjit-manna/5a00ca900d27448ddbdb224c38b0be8b to your computer and use it in GitHub Desktop.
React JS virtuall scroll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { Virtuoso, VirtuosoHandle } from 'react-virtuoso'; | |
import { useEffect, useRef, useState } from 'react'; | |
export default function FooterVirtualScroll({ noMoreData, list }: { noMoreData: boolean; list: Array<any> }) { | |
return ( | |
<div className='text-center py-4 text-gray-150'> | |
{!noMoreData && list.length > 0 && ( | |
<>Loading ...</> | |
)} | |
{noMoreData && list.length > 0 && ( | |
<>No more data!</> | |
)} | |
</div> | |
); | |
} | |
export default function TodoListScreen() { | |
const list = useRef<any>(); | |
const [todoList, setTodoList] = useState<Array<any>>([]); | |
const [noMoreData, setNoMoreData] = useState(false); | |
const footerComponent = () => { | |
return ( | |
<FooterVirtualScroll noMoreData={noMoreData} list={todoList} /> | |
); | |
}; | |
function Row( | |
index: number, | |
todo: any, | |
) { | |
return ( | |
<> | |
<TodoView key={todo.id || index} todo={todo} /> | |
</> | |
); | |
} | |
function loadMore() { | |
// Call Api for next page data | |
// come from api | |
const newTodosArray = []; | |
if (newTodosArray.length > 0) { | |
// Add new arrays | |
const list = todoList.concat([]); | |
setTodoList(list); | |
} else { | |
setNoMoreData(false); | |
} | |
} | |
function handleEndReach() { | |
if (!noMoreData) { | |
loadMore(); | |
} | |
} | |
useEffect(() => { | |
// Call Api and set Todo list | |
setTodoList([]); | |
}, []); | |
return ( | |
<div> | |
<Virtuoso | |
ref={list} | |
data={todoList} | |
endReached={handleEndReach} | |
overscan={200} | |
itemContent={Row} | |
components={{ Footer: footerComponent }} | |
/> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment