Skip to content

Instantly share code, notes, and snippets.

@Evavic44
Last active October 16, 2024 19:54
Show Gist options
  • Save Evavic44/1dd0a79a8fb4ce14e506243339d6f2fb to your computer and use it in GitHub Desktop.
Save Evavic44/1dd0a79a8fb4ce14e506243339d6f2fb to your computer and use it in GitHub Desktop.
Cloudinary reel video implementation using Cloudinary React SDK
"use client";
import { useRef } from "react";
import { Cloudinary } from "@cloudinary/url-gen";
import {
  AdvancedVideo,
  AdvancedImage,
  lazyload,
  accessibility,
} from "@cloudinary/react";
import { crop } from "@cloudinary/url-gen/actions/resize";

interface props {
  publicId: string;
  poster: string;
  height?: number | string;
  width?: number | string;
  controls: boolean;
  loop?: boolean;
  autoplay: boolean;
  muted: boolean;
  playsInline?: boolean;
  alt?: string;
}

const cld = new Cloudinary({
  cloud: { cloudName: "your-cloudinary-cloudname" },
});

export default function MediaComponent({
  publicId,
  poster,
  controls,
  loop,
  autoplay,
  muted,
  width,
  height,
  playsInline,
  alt,
}: props) {
  const playerRef = useRef<AdvancedVideo | any>();
  let shouldPlayVideo;

  const videoLoaded = function () {
    shouldPlayVideo = true;
    if (shouldPlayVideo) {
      playerRef.current.videoRef.current?.play();
    }
  };

  const pauseVideo = function () {
    playerRef.current.videoRef.current?.pause();
    playerRef.current.videoRef.current?.load();
  };

  return (
    <div className="relative group" onMouseLeave={pauseVideo}>
      <AdvancedImage
        className="relative z-10"
        alt={alt}
        cldImg={cld
          .image(poster)
          .setAssetType("video")
          .format("auto:image")
          .resize(crop(width, height))}
      />
      <AdvancedVideo
        ref={playerRef}
        onLoadedData={videoLoaded}
        className="absolute top-0 left-0 opacity-0 z-0 group-hover:z-20 group-hover:opacity-100 transition-opacity duration-700 bg-zinc-900"
        loop={loop}
        autoPlay={autoplay}
        muted={muted}
        cldVid={cld.video(publicId).resize(crop(width, height))}
        plugins={[lazyload(), accessibility()]}
        playsInline={playsInline}
        controls={controls}
      />
    </div>
  );
}

Example Usage

const reels: CloudinaryType[] = await getMedia("reels");

<MediaComponent
  autoplay={true}
  muted={true}
  loop={true}
  key={reel.id}
  height={1280}
  width={720}
  publicId={reel.name}
  poster={reel.name}
  controls={false}
  playsInline={true}
  alt={`${reel.name.split("/")[1]} reel project`}
 />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment