Use the returned rive instance with other hooks when you need data binding.import React, { useEffect } from "react";
import { useRive, useViewModelInstanceNumber } from "@rive-app/react-webgl2";
export default function App() {
const { rive, RiveComponent } = useRive({
// Load a local .riv file or use a hosted URL.
src: "quick_start_health_bar.riv",
// Be sure to specify the correct state machine (or animation) name
stateMachines: "State Machine 1",
// Autoplay the state machine
autoplay: true,
// This uses the view model instance defined in Rive
autoBind: true,
});
// Get the bound view model instance
const vmi = rive?.viewModelInstance;
// Access the bound numeric `health` field and its setter from the view model instance.
const { value: health, setValue: setHealth } = useViewModelInstanceNumber(
"health",
vmi
);
useEffect(() => {
// Set the health value
setHealth(10);
}, [rive, setHealth]);
return (
<RiveComponent />
);
}
The Rive canvas sizes itself based on its container. If nothing appears, make sure the parent element has a defined width and height.
Use the imperative runtime when you want to create and manage the Rive instance yourself. In React, this is usually done with useEffect and a canvas ref.Imperative usage uses the Web JavaScript runtime package, such as @rive-app/webgl2, instead of a React package.
import React, { useEffect, useRef } from "react";
import { Rive, Fit, Layout } from "@rive-app/webgl2";
import "./styles.css";
export default function App() {
const canvasRef = useRef();
useEffect(() => {
const riveInstance = new Rive({
// Load a local .riv file or use a hosted URL.
src: "quick_start_health_bar.riv",
// Be sure to specify the correct state machine (or animation) name
stateMachines: "State Machine 1", // Name of the State Machine to play
canvas: canvasRef.current,
autoplay: true,
autoBind: true, // This uses the view model instance defined in Rive
onLoad: () => {
// Prevent a blurry canvas by using the device pixel ratio
riveInstance.resizeDrawingSurfaceToCanvas();
},
});
const handleResize = () => {
if (riveInstance) {
riveInstance.resizeDrawingSurfaceToCanvas();
}
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
riveInstance.cleanup();
};
}, []);
return <canvas ref={canvasRef} style={{ width: "100%", height: "50vh" }} />;
}