Skip to content

🎥 Make videos programmatically with React

`@remotion/rive`: Allow to pass a ref

Jonny Burger6b5ab01cc70b
diff --git a/packages/rive/src/RemotionRiveCanvas.tsx b/packages/rive/src/RemotionRiveCanvas.tsx
index 0aa0edc152..99ba270971 100644
--- a/packages/rive/src/RemotionRiveCanvas.tsx
+++ b/packages/rive/src/RemotionRiveCanvas.tsx
@@ -6,7 +6,14 @@ import type {
RiveCanvas,
} from '@rive-app/canvas-advanced';
import riveCanvas from '@rive-app/canvas-advanced';
-import React, {useEffect, useMemo, useRef, useState} from 'react';
+import React, {
+ forwardRef,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
import {
continueRender,
delayRender,
@@ -30,14 +37,26 @@ interface RiveProps {
onLoad?: onLoadCallback | null;
}
-export const RemotionRiveCanvas: React.FC<RiveProps> = ({
- src,
- fit = 'contain',
- alignment = 'center',
- artboard: artboardName,
- animation: animationIndex,
- onLoad = null,
-}) => {
+export type RiveCanvasRef = {
+ getAnimationInstance: () => LinearAnimationInstance | null;
+ getArtboard: () => Artboard | null;
+ getRenderer: () => CanvasRenderer | null;
+};
+
+const RemotionRiveCanvasForwardRefFunction: React.ForwardRefRenderFunction<
+ RiveCanvasRef,
+ RiveProps
+> = (
+ {
+ src,
+ fit = 'contain',
+ alignment = 'center',
+ artboard: artboardName,
+ animation: animationIndex,
+ onLoad = null,
+ },
+ ref,
+) => {
const {width, fps, height} = useVideoConfig();
const frame = useCurrentFrame();
const canvas = useRef<HTMLCanvasElement>(null);
@@ -56,6 +75,24 @@ export const RemotionRiveCanvas: React.FC<RiveProps> = ({
artboard: Artboard;
} | null>(null);
+ useImperativeHandle(
+ ref,
+ () => {
+ return {
+ getAnimationInstance() {
+ return rive?.animation ?? null;
+ },
+ getArtboard() {
+ return rive?.artboard ?? null;
+ },
+ getRenderer() {
+ return rive?.renderer ?? null;
+ },
+ };
+ },
+ [rive],
+ );
+
useEffect(() => {
riveCanvas({
locateFile: () =>
@@ -162,3 +199,7 @@ export const RemotionRiveCanvas: React.FC<RiveProps> = ({
return <canvas ref={canvas} width={width} height={height} style={style} />;
};
+
+export const RemotionRiveCanvas = forwardRef(
+ RemotionRiveCanvasForwardRefFunction,
+);