(React onScroll) How to trigger onScoll event

I’m trying to animate a business card by altering its opacity depending on its location in the browser, creating somewhat of a fade-in, fade-out look, but this will differ from a keyframes animation as its not timed but purely dependant on the position of the scrollbar (kind of like the Apple product website). I’m doing this in react and am using the onScroll JSX attribute, but it doesn’t seem to be firing. Each Card is 100vh in height.

import React, {useState} from 'react'
import './styles.css'
import Card1 from './Card1'

function App() {
  const [idx, setIdx] = useState(1); 
  
  const iterate = () => {
    console.log('scrolled')
  } 

  return (
    <div className="outer-container" onScroll={iterate}>
        <Card1 num = {idx}/> 
        <Card1 num = {idx}/> 
        <Card1 num = {idx}/> 
        <Card1 num = {idx}/> 
        <Card1 num = {idx}/> 
        <Card1 num = {idx}/> 
    </div>); 
}

export default App;

Any help would be much appreciated!

Answer

This might be what you’re looking for:

import React, { useState, useEffect } from "react";
import "./styles.css";
import Card1 from "./Card1";

function App() {
  const [idx, setIdx] = useState(1);

  useEffect(() => {
    const handleScroll = () => {
      // code here will be executed on the scroll event
    };

    window.addEventListener("scroll", handleScroll);

    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  const iterate = () => {
    console.log("scrolled");
  };

  return (
    <div className="outer-container" onScroll={iterate}>
      <Card1 num={idx} />
      <Card1 num={idx} />
      <Card1 num={idx} />
      <Card1 num={idx} />
      <Card1 num={idx} />
      <Card1 num={idx} />
    </div>
  );
}

export default App;

Here’s a related post with a solution that may help you: Changing styles when scrolling React