Home > Software engineering >  Lazy loading element in typescript hook not working
Lazy loading element in typescript hook not working

Time:09-14

I've implemented a lazy loading hook, but for some reason the carousel component is not loading at all. I've got it from here: https://betterprogramming.pub/lazy-loading-in-next-js-simplified-435681afb18a

This is my child that I want to render when it's in view:

import { useRef } from "react";
import Carousel from "../components/carousel";
import useOnScreen from "../hooks/useOnScreen";

// home page
function HomePage() {
  const carouselRef = useRef();
  const carouselRefValue = useOnScreen(carouselRef);
  return (
        <div className="snap-y">
          {/* 1 */}
          <div className="flex justify-center items-start relative min-h-[calc(100vh_-_5rem)] bg-black snap-start ">
            {/* Cone */}
            <div className="absolute w-full max-w-full overflow-hidden min-w-fit cone animate-wiggle"></div>
    
            <div className="grid justify-center grid-cols-4 max-w-7xl">
//Content
          </div>
    
          {/* 2 */}
          <div className="z-20 pb-4 bg-black snap-start" ref={carouselRef.current}>
            {carouselRefValue && <Carousel />}
          </div>
    
          {/* 3 */}
          <div className="flex items-start justify-center py-32 min-h-fit bg-slate-50 snap-start">
           //More content
        </div>
      );
    }

export default HomePage;

useOnScreen hook:

import { useState, useEffect } from "react";
const useOnScreen = (ref: any) => {
  const [isIntersecting, setIntersecting] = useState(false);
  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => setIntersecting(entry.isIntersecting));
    if (ref.current) {
      observer.observe(ref.current);
    }
  }, []);
  return isIntersecting;
};
export default useOnScreen;

Edit: Needed to add const carouselRef = useRef() as React.MutableRefObject<HTMLInputElement>; paired with @asynts's answer.

CodePudding user response:

This is incorrect:

<div className="z-20 pb-4 bg-black snap-start" ref={carouselRef.current}></div>

it should be:

<div className="z-20 pb-4 bg-black snap-start" ref={carouselRef}></div>
  • Related