React infinite scroll

Zain Ahmed
3 min readMay 17, 2020

--

in this artical you can learn how we can create infinite scroll on react, any questions ask about that “i want to create on scroll fetch api”

topic: “suppose you have a api which give you user details and this api receive some params like pages no on this basis it give you limited results like on page value 1 api will give 10 results on page 2 apis will give you next 10 users result , so i want to make a table which on first call get user data from page 1 params and after on scroll to end result api will recall with page increment and give me next 10 results so i can merge this new result with old one and show on table ,

let start

for that i am using functional component you can use class base also

step 1

Define variables

const [data, setData] = useState([]) // default value null array

let [page, setPage] = useState(1) // default value 1

const [loader, setLoader] = useState(true) // default value true

api url : `https://randomuser.me/api/?page=${page}&results=10`

as you can see on ss i create table and give class table-wrap and give css

.table-wrap {

height: 300px;

overflow-y: auto;

}

you can check the api response by hit this url so i don’t need to explain the structure

also i create onscroll event on div called laodMoreHandle

step 2: now we will create fetchUser func to call api

as you can see in image this function get a params call page which i initialized earlier which value is currently 1 so on api call we can get data of page 1 with limit 10 and on .then func we made a condition which is that .

“if page value is 1 data will store in variable simple and if page value is greater then 1 the api result merge with old data , so we can get latest data too”.

step 3 : on to the final step we have to create a func which will call on scroll to bottom

ok so this function also has a condition let examine it.

“the function will call on every scroll and we can get some data on “e” e.target.scrollHeight : it will give you current scroll height , scrollTop: it will give you the distance from top, clientHeight : it will give you height which we assign to main div, now the condition is if all this after minu has value less then 50 then save true on bottom variable else false . and if bottom is true then make increment on page variable then call api and then set page value.”

i hope you can get all the thing correctly remember practice make the man perfect so try it then learn more

--

--

Zain Ahmed
Zain Ahmed

Written by Zain Ahmed

Hello everyone, I am Zain Anmed a software engineer by profession, passionate about trying different technologies and trying some other cool stuff.

No responses yet