glennreyes / react-countup

💫 A configurable React component wrapper around CountUp.js
https://tr8tk.csb.app/
MIT License
2.01k stars 132 forks source link

Change class onEnd #107

Closed modestotech closed 5 years ago

modestotech commented 5 years ago

I'm struggling to make the counter animate onEnd. More specifically I want the text to get bubble up big, and then go back.

The relevant scss is as follows

  .number {
    font-style: italic;
    font-size: 1.5rem;

    .enlargened {
      animation-name: enlargen;
      animation-duration: 1s;
      animation-fill-mode: forwards;
    }
  }

What I want is to apply className directly, and when the counter has reached its end, I want to append enlargened to the className, which will make the animation happen.

On a normal element I'd do it easily with something like document.getElementByClassName('number').className ='number enlargened'

But no I don't manage with this component, I've tried using refs and accessing the element directly with different getElement syntaxes, without prevail. My last try was with a wrapper div, but didn't work either.

It might be related to me always getting two div (although I've only declared one). The following setup

        <CountUp
          duration={duration}
          end={count}
          prefix="  "
          onEnd={() => {
            console.log(document.getElementsByClassName('number'));
          }}
          useEasing={false}
        />

Prints the following in console.log: image

Let me know if I'm using the component wrong, or if you need any more information.

whitecrownclown commented 5 years ago

@modestotech I'm not exactly sure of your issue, but it does seem like you're not getting the node correctly.

From what i've tested you could do this in at least 2 ways, assuming enlarged is your animation className:

let nodeRef;

function onEnd() {
   nodeRef.current.classList.add('enlarged'); // or document.getElementById('counter').classList.add('enlarged');
}

<CountUp start={1} end={1000000} delay={0} duration={2} onEnd={onEnd}>
      {({ countUpRef }) => {
        nodeRef = countUpRef; // save the ref
        return <span id="counter" ref={countUpRef} />; // or grab the element by an id
      }}
</CountUp>

Hope it helps, you can also have a look at this codepen.

modestotech commented 5 years ago

Thanks, that works as expected, I got confused with the ref handing.