3

I'm trying to create an animated timeline on react with a map function and intersection observer so each part of the timeline loads sequentially.

I'm having trouble with the refs as I believe the ref only links to the last item on the map? I have had a look around and can't seem to find anything.

Here is my code:

import dataxp from '../Data/data-xp'
import TimelineItem from './TimelineItem'

function useOnScreen(options) {
  const ref = React.createRef()
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      setVisible(entry.isIntersecting);
    }, options);

    if (ref.current) {
      observer.observe(ref.current)
    }

    return () => {
      if (ref.current) {
        observer.unobserve(ref.current)
      }
    }
  }, [ref, options])

  return [ref, visible]
}

function Timeline() { 
  const [ref, visible] = useOnScreen({rootMargin: '-500px'})

  return (
  dataxp.length > 0 &&  (
    <div className='timeline-container'>
      <div className='title-container'>
        <h1 className='xp-title'>EXPERIENCE</h1>
      </div>
        {visible ? (dataxp.map((data, i) => (
          <TimelineItem data={data} key={i}  ref={ref}/> 
          )
        )) : (
          <div style={{minHeight: '30px'}}></div>)}
      <div className='circle-container'>
        <div className='end-circle'> </div>
      </div>
    </div>
    )
  )
}


export default Timeline
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Darbjm
  • 31
  • 3
  • 1
    Yes, I think your observer will only get one reference. I've created a [demo](https://codesandbox.io/s/icy-https-u8egv) where I'm adding multiple references to the observer. Fast scrolling is still a problem. Maybe I'll have a look into this tomorrow. – AWolf Mar 31 '20 at 22:39
  • @AWolf anything new? – Lucas Steffen Feb 11 '21 at 00:43
  • @LucasSteffen I've improved the demo. Now it's also working with faster scrolling. Still no animation as I'm not sure how it should look. But the issue with my previous code was that the intersection observer is doing a single callback for multiple elements. So I had to handle every change. – AWolf Feb 17 '21 at 12:12
  • @Darbjm Have you been able to solve this yet? This is quite a problem using `.map` with Intersection Observer but I haven't seen any solution around – KYin Apr 25 '22 at 07:20

0 Answers0