import React, { Children, useCallback, useRef, JSX } from 'react' import { usePostHog } from '../hooks' import { VisibilityAndClickTracker } from './internal/VisibilityAndClickTracker' export type PostHogCaptureOnViewedProps = React.HTMLProps & { name?: string properties?: Record observerOptions?: IntersectionObserverInit trackAllChildren?: boolean } function TrackedChild({ child, index, name, properties, observerOptions, }: { child: React.ReactNode index: number name?: string properties?: Record observerOptions?: IntersectionObserverInit }): JSX.Element { const trackedRef = useRef(false) const posthog = usePostHog() const onIntersect = useCallback( (entry: IntersectionObserverEntry) => { if (entry.isIntersecting && !trackedRef.current) { posthog.capture('$element_viewed', { element_name: name, child_index: index, ...properties, }) trackedRef.current = true } }, [posthog, name, index, properties] ) return ( {child} ) } /** * PostHogCaptureOnViewed - Track when elements are scrolled into view * * Wraps any children and automatically sends a `$element_viewed` event to PostHog * when the element comes into the viewport. Only fires once per component instance. * * @example * ```tsx * *
Important content here
*
* * // With custom properties * * * * * // With custom intersection observer options * *