Skip to content

🎥 Make videos programmatically with React

autoplay on focus

Jonny Burger38d3bc23c455
diff --git a/packages/docs/components/Player/features.tsx b/packages/docs/components/Player/features.tsx
index 5733636dde..6b81a447eb 100644
--- a/packages/docs/components/Player/features.tsx
+++ b/packages/docs/components/Player/features.tsx
@@ -25,7 +25,7 @@ export const PlayerFeatures: React.FC = () => {
</div>
<div style={{ width: 20, height: 30 }} />
<div className={styles.half}>
- <PlayerExample name={name} color={color} />
+ <PlayerExample name={name} color={color} autoPlayOnFocus />
</div>
</div>
<div className={styles.row}>
diff --git a/packages/docs/components/PlayerExample.tsx b/packages/docs/components/PlayerExample.tsx
index 2f7bcb3b51..0aebeafb91 100644
--- a/packages/docs/components/PlayerExample.tsx
+++ b/packages/docs/components/PlayerExample.tsx
@@ -1,28 +1,67 @@
-import { Player } from "@remotion/player";
+import { useEffect } from "react";
+import { useState } from "react";
+import { useRef } from "react";
+import { useCallback } from "react";
+import { Player, PlayerRef } from "@remotion/player";
import React from "react";
import { ColorDemo } from "./ColorDemo";
import "./input-fields.css";
-export const PlayerExample: React.FC<{ name: string; color: string }> = ({
- name,
- color,
-}) => {
+export const PlayerExample: React.FC<{
+ name: string;
+ color: string;
+ autoPlayOnFocus?: boolean;
+}> = ({ name, color }) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ const playerRef = useRef<PlayerRef>(null);
+
+ const [isIntersecting, setIsIntersecting] = useState(false);
+ const callback: IntersectionObserverCallback = useCallback(
+ (newData) => {
+ setIsIntersecting(newData[0].isIntersecting);
+ if (isIntersecting) {
+ playerRef.current?.play();
+ } else {
+ playerRef.current?.pause();
+ }
+ },
+ [isIntersecting]
+ );
+ useEffect(() => {
+ const { current } = containerRef;
+ if (!current) {
+ return;
+ }
+
+ const observer = new IntersectionObserver(callback, {
+ root: null,
+ threshold: 1,
+ });
+ observer.observe(current);
+
+ return () => observer.unobserve(current);
+ }, [callback]);
+
return (
- <Player
- component={ColorDemo}
- compositionWidth={1280}
- compositionHeight={720}
- controls
- durationInFrames={350}
- fps={30}
- inputProps={{
- name,
- color,
- }}
- style={{
- width: "100%",
- }}
- loop
- />
+ <div ref={containerRef}>
+ <Player
+ ref={playerRef}
+ component={ColorDemo}
+ compositionWidth={1280}
+ compositionHeight={720}
+ controls
+ durationInFrames={350}
+ fps={30}
+ inputProps={{
+ name,
+ color,
+ }}
+ style={{
+ width: "100%",
+ }}
+ loop
+ />
+ </div>
);
};