0

I could not find an answer here AOS Library not working except for on refresh

I am making a react app and wanted to use AOS for animating https://michalsnik.github.io/aos/.

I have a functional component with this code

import AOS from 'aos';
import 'aos/dist/aos.css';


export default function Portfolio() {

  useEffect(() => {
    AOS.init({
      duration: 1000
    });
    AOS.refresh();
  }, []);

return(
 <span className="bumper">Projects </span>
      
      <div data-aos="fade-in">
      <h3>  Hello! </h3>
      </div>
)

When I first load the page, the screen only says "Projects", and there is no "Hello!", but when I edit the "Hello!" to "Hi!" and React auto-refreshes I see the animation come in.

What is possibly happening here?

I am in the React Dev environment

    "react-dom": "^18.1.0",
    "react": "^18.1.0",
    "aos": "^3.0.0-beta.6",

Marko
  • 1
  • 2
  • From a quick google search I see that ```aos.refresh()``` could cancel durations, could you try without ? – JeanJacquesGourdin Jun 30 '22 at 18:44
  • Is the closing `h2` tag there for a reason? – Jared A Sutton Jun 30 '22 at 18:51
  • No sorry, I'll edit the h2 out. – Marko Jun 30 '22 at 19:43
  • The result is the same, with the `AOS.refresh()` edited out. Hmmm – Marko Jun 30 '22 at 19:44
  • You might try putting a `setTimeout` around the AOS calls, just in case has to wait for something to be ready. You also might try `useLayoutEffect` instead of `useEffect`. I'm not familiar with AOS, but it seems like it might affect the DOM? – Roy J Jun 30 '22 at 19:55
  • AOS=animation on scroll, it's just to animate when you scroll to an element. `useLayoutEffect` gives the same response as `useEffect`, `setTimeout` did not work around AOS.refresh either. Thank you for the ideas though – Marko Jun 30 '22 at 20:08

1 Answers1

0

React V18 added a rerender for useEffect Hook. So now it's rerendering twice on strict mode, enabled. There are two ways to tackle this. Either you disable strict mode (Which I totally don't recommend), or you undo what happens on the first render from happening by returning a callback that works on unmounting the component.

useEffect(() => {
    AOS.init({
      duration: 1000
    });
    AOS.refresh();
return () => {
//Kill your animation not sure of the syntax for AOS. 
AOS.kill()
//Or 
AOS.refresh()
}
  }, []);
  • I just tried this on my react app useEffect(() => { AOS.init(); return () => { AOS.refresh(); }; }, []); It worked fine. Firstly it was juts like yours. It wasn't working unless you refresh. Now it works from the first render – Mohammed-Moniem Nov 02 '22 at 18:08