Philip Yoon
Philip Yoon

Reputation: 51

Is setRef possible on duplicate cloneElement?

I want to operate onIntersect through setRef on duplicated cloneElements without a div, but onIntersect does not work when there are two cloneElements. How can I make Detect Result appear in onIntersect?

import Link from 'next/link'

interface useIntersectionObserverProps {
  root?: null
  rootMargin?: string
  threshold?: number
  onIntersect: IntersectionObserverCallback
}

export default function Test() {
  return (
    <CloneImpression>
      {/* when i comment out CloneClick Component it work! */}
      <CloneClick> 
        <Link href={'/'}>impression test</Link>
      </CloneClick>
    </CloneImpression>
  )
}

const CloneClick = ({ children }: { children: React.ReactElement }) => {
  return cloneElement(children, {
    onClick: (...args: any[]) => {
      console.log('onClick')

      if (children.props && typeof children.props['onClick'] === 'function') {
        return children.props['onClick'](...args)
      }
    },
  })
}

const CloneImpression = ({ children }: { children: React.ReactElement }) => {
  console.log('children', children)

  const onIntersect: IntersectionObserverCallback = ([{ isIntersecting }]) => {
    console.log(`Detect Result : ${isIntersecting}`)
  }

  const { setTarget } = useIntersectionObserver({ onIntersect })
  return cloneElement(children, {
    ref: setTarget,
  })
}

const useIntersectionObserver = ({
  root,
  rootMargin = '0px',
  threshold = 0,
  onIntersect,
}: useIntersectionObserverProps) => {
  const [target, setTarget] = useState<HTMLElement | null | undefined>(null)

  console.log('target', target)
  useEffect(() => {
    if (!target) return

    const observer: IntersectionObserver = new IntersectionObserver(onIntersect, { root, rootMargin, threshold })
    observer.observe(target)

    return () => observer.unobserve(target)
  }, [onIntersect, root, rootMargin, target, threshold])

  return { setTarget }
}

when i trying with in comment the console.log('target', target) result got null but i want to get the target <a href="/store">impression test</a> and fire the onIntersect function

Upvotes: 0

Views: 21

Answers (0)

Related Questions