React - Swiper conditional rendering based on screen size

0 votes
179 views
added Mar 26 in React by lcjr First Warrant Officer (11,780 points)
// Head area 
function GalleryComponent(props) {
  const gallerySwiperNodeRef = React.createRef();
  .....
  
  //screen hook
  const [isMobileView, setIsMobileView] = useState(false);
  
  
  //screen hook
  useEffect(() => {
    const handleResize = () => {
      setIsMobileView(window.innerWidth < 576);
    };

    handleResize();

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);
  
  // the conditional area
  const gallery = isMobileView ? (
    image && image.length > 0 ? (
      <div
        className="desktop-image-link swiper-slide mobile-image-link"
        key={0}
        onClick={() => togglLightbox(0, 0)} // Open lightbox with all images
      >
        <img
          data-src={image[0].src}
          className="desktop-image-item swiper-lazy mobile-image-item"
          alt={image[0].alt}
        />
        <div className="swiper-lazy-preloader" />
      </div>
    ) : null
  ) : (
    image &&
    image.map((obj, i) => (
      <div
        className="desktop-image-link swiper-slide mobile-image-link"
        key={i}
        onClick={() => togglLightbox(0, i)}
      >
        <img
          data-src={obj.src}
          className="desktop-image-item swiper-lazy mobile-image-item"
          alt={obj.alt}
        />
        <div className="swiper-lazy-preloader" />
      </div>
    ))
  );

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...