r/learnreactjs • u/Syokai • Jun 11 '24
Help Needed with Animating Count Changes in a Component
Hey everyone,
I'm hoping someone can help me with an animation I'm trying to create. I have a component that displays a count, like "2 selected." I want to animate the count when it increases or decreases.
Here's the animation I'm aiming for (let's say the current count is 2):
- When increasing: The number 2 slides up and fades out, and the new number 3 slides up from the bottom and fades in.
- When decreasing: The number 2 slides down and fades out, and the new number 1 slides down from the top and fades in.
I have a working solution that looks like this: Code Example and Video Preview.
The issue I'm running into is that the CSS <style> gets injected in a way that's not ideal. I want to refine this aspect.
Additionally, it would be fantastic if someone could make the animation so that when the number is 2 or 3 digits long, only the digits that are changing animate. For example, increasing from 103 to 104 should only animate the last digit and not the whole number.
Any suggestions or improvements would be greatly appreciated!
2
u/detached_obsession Jun 12 '24
Since you're already using Material UI, I would advise to leverage their existing functionality. The mui docs have examples for the Slide transition you describe, particularly they have an example with a parent container, basically a wrapper div with an overflow hidden to hide the elements sliding up or down out of it. They also have callbacks like
onEnterandonExitthat you could use.As for your request to animate part of the digit, I think the only way to do it is to split a digit up, from 122 for example to
["1","2","2"]. Like this you can iterate over them and animate the ones that have changed by checking the previous one at a specific index. For example if you went from 122 to 123, the value at index 2 has changed but everything else has stayed the same. Placing each digit in their own<span />will let you animate the ones changing.1
u/MementoLuna Jun 12 '24
Why do you need to inject a style tag? You can just add it to your actual css file or HTML head tag. Anything dynamic that you're doing with it I'd suggest having it as two separate classes and just switching the classes in your react component based on the variable