JavaScript events and methods

Control the DynTube Player in React

Render the iframe declaratively, then create the DyntubePlayer SDK instance in a browser-side effect. Keep the player ID stable for the mounted video and return cleanup that removes every event subscription. This prevents duplicate handlers during remounts and route changes.

React component with SDK lifecycle

ControlledVideo.tsx
import { useEffect, useRef, useState } from "react";

export function ControlledVideo({ embedKey }) {
  const frameId = `dyntube-${embedKey}`;
  const playerRef = useRef(null);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    let active = true;
    const cleanups = [];

    void import("https://embed.dyntube.com/v2/embed-sdk.js").then(async ({ DyntubePlayer }) => {
      const player = new DyntubePlayer(`#${frameId}`, { playerId: frameId });
      playerRef.current = player;
      await player.ready;
      if (!active) return;
      setReady(true);
      cleanups.push(player.on("ended", () => console.log("complete")));
    });

    return () => {
      active = false;
      cleanups.forEach((unsubscribe) => unsubscribe());
      playerRef.current = null;
    };
  }, [frameId]);

  return <>
    <iframe id={frameId}
      src={`https://dyn.tube/embed/video/${encodeURIComponent(embedKey)}?playerId=${encodeURIComponent(frameId)}`}
      title="Course lesson" allow="autoplay; fullscreen; encrypted-media; picture-in-picture"
      allowFullScreen />
    <button disabled={!ready} onClick={() => playerRef.current?.play()}>Play</button>
  </>;
}

React-specific checks

  • Run SDK setup only in the browser; server rendering can output the iframe itself.
  • Do not create an SDK instance during render.
  • Guard asynchronous setup so an unmounted component is not updated.
  • Store the player instance in a ref instead of state.
  • Disable custom controls until player.ready resolves.
  • Unsubscribe on unmount and recreate the integration when the embed key changes.

Catch import, readiness, and command failures in production and provide an accessible playback message. Test React Strict Mode, conditional rendering, multiple players, route transitions, and protected video so lifecycle defects are visible before release.

Something missing or wrong here? Tell us and we will correct it. New to DynTube? Start with uploading and embedding.