What is it?
I had this need to understand how that youtube's view count thing works. I'm talking about that number digits on a video views going up with an animated scrolling while watching a video for a while.
So I had to break it down using React and also made a react component as an npm package. Check it out here.
Simple state update
From the looks of it, it was simple, but it was not.
Let's start from the begining.
We have the parent component that calls to render the Metered count component.
Its goal is to update the count
value whenever it needs to.
So the child component (this metered count component) takes the new value as a prop and updates it to the latest value.
This is simple without the animation part. Because when the prop value count updates and if we render it in the child component it gets updated by react.
Breaking it down
It took me few hours to implement this using javascript but to do the same in react, was hard and took some time to comprehend.
If you want to think through this problem and try now is the time.
...
Let's break it down now.
There are few steps
- Containerize the digits to a array for the value as
count
- Calculating the difference values as
steps
between previous and current digits - Animating each differences if the difference is greater than one
Using react we can have a useState hook to store the number as an object array.
An object of this array contains properties steps
(which stores the difference of previous and current digit as a number) and the content
(which stores the new values to animate as a array)
i.e.
Let's say the value for count
by parent comes as 0. In youtube's terms let's say the views count is 0.
So the containers array will be like this
[{steps: 0, content: [0]}]
At this time let's say the count value goes up to 12. So what will happen now?
The new containers value should be like this below after calculations of the differences of the digits (left to right of the number).
old count value = '00'
new count value = '12'
[{steps: 1, content: [0, 1]}, {steps: 2, content: [0, 1, 2]}]
See the graphic below
In this graphical representation red square is the visible area. The overflowed area is hidden using css property overflowY: hidden
. It should also hide the scrollbar that comes with it.
So the next thing to do is animating the change.
With react, once the containers gets updated that change is listened by a useEffect hook that do the animation.
To do this it requires an animate function that animates all the digits of a single container. In javascript, I handled this using element.scrollTo
function but in react I used element.animate
function that changes translatesY css property thus making the div go up.
Note that fill
property for animation function needs to be forward
Otherwise the animation resets to previous value.
See the graphic below
See the source code GitHub.
Thanks for Reading! :)
Top comments (0)