How to make an array.length counter update on user scroll using ReactJS

Viewed 425

I'm trying to add a simple counter in the bottom of my app like this one:

counter image

And it is very simple atm, 80 is my array.length that is being populated through my axios request.

<div>{people.length.toLocaleString()}</div>

And as I scroll down the page, using react-infinite-scroll, the number goes up and up and this is just fine. What I'm trying to do is subtract the number as the user goes back up the page.

Is this something harder than I'm thinking? If so, don't give me the full answer, just give me the path to follow. Thanks.

This is what I'm trying to accomplish: https://mkorostoff.github.io/hundred-thousand-faces/

3 Answers

you can do by using scroll event with window.innerHeight and the element bottom height to check whether its available inside the display window.

You can try like this using onscroll event which is available in library itself.

let counter = 0;
 [listofElement].find(ele => {
  var conditionHeight = window.innerHeight;
  var cordinat = ele.getBoundingClientRect().top;
  counter++;
  return conditionHeight < cordinat;
});

You can check here with sample working part.

Edit rough-violet-1qysy

Looking at the source of the page you've linked, the code uses this function to get the size of the page:

function getScrollPercent() {
  var face_width = document.getElementById('first').clientWidth;
  var face_height = document.getElementById('first').clientHeight;
  var body = document.documentElement || document.body;
  var faces_per_row = Math.floor(main.clientWidth / face_width);
  var total_height = total / faces_per_row * face_height;
  var scroll_percent = (body.scrollTop - main.offsetTop + body.clientHeight) / total_height;
  var count = Math.floor(scroll_percent * total);

  var chunked_count = count - (count % faces_per_row);

  if (chunked_count > 0) {
    counter.classList = "fixed";
  }
  else {
    counter.classList = "";
  }
  return (chunked_count > 0) ? chunked_count : 0;
}

The essential bit is var scroll_percent = (body.scrollTop - main.offsetTop + body.clientHeight) / total_height;. Basically, if you can calculate your total height (assuming that isn't infinite), then you can use body.clientHeight, +/- offsets, divided by totalHeight to figure out how far down the page you are. Call this from an event listener on scroll, and you should be good to go.

Incidentally, if this is the infinite scroll library you're talking about using, it's no longer maintained in favor of react-infinite-scroller.

using react-infinite-scroll, you can't back axios request results or remove generated doms.

The solution is calculating width and height of every doms and calculate offset.

Check how many doms are above the scrollReact and so so.

Related