0

Context:

I want to add an AOS-effect to multiple divs filled with data from a server, which are rendered after the initial render:

import {useEffect, useState} from "react";

export const Test = () => {
  const [data, setData] = useState([]);
  
  async function fetchData() {
    //Example fetch request
    const response = await fetch(API, {method:"GET"});
    const json = await response.json();
    setData(json);
  }
  
  useEffect(() => {fetchData();}, []);
  
  return (
    <>
      {
        data.map((text, index) => {
          //add aos effect to each div
          <div key={index}>
            {text}
          </div>
        });
      }
    </>
  )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

What I've tried:

I tried to import AOS and add it as in this question:

<div key={index} data-aos="fadeIn"></div>

This had no effect at all.

I also looked at react-animate-on-scroll, but it is not compatible with react v. 18.1.0:

incompatible with react 18.1.0

Question:

How can I get animate on scroll (AOS) to work on fetched data in react?

Philip F.
  • 1,167
  • 1
  • 18
  • 33

3 Answers3

0

I found the error. I had to import the aos css files as well:

import AOS from "aos";
import "aos/dist/aos.css";
Philip F.
  • 1,167
  • 1
  • 18
  • 33
0

Did you initialize AOS in the first place?

  <script>
    AOS.init();
  </script>

You might need to refresh AOS due to reacts rendering nature, which renders new html elements on each component update.

  AOS.refresh();
elsybilo
  • 56
  • 6
-1

I would try giving a class which animates or using Intersection Observer

user18821127
  • 318
  • 1
  • 8
  • Can you maybe ellaborate which class to add or how to use Intersection Observer, or provide some links? – Philip F. Jul 07 '22 at 08:59