Handling Rive Events
Rive Events are a powerful feature that allows your animations to communicate back to your application code. You can create events in the Rive editor that get fired from state machine timelines. Your React application can then listen for these events and react accordingly.
Listening for Events
To listen for Rive events, you first need access to the rive
instance from the useRive
hook. Once you have the instance, you can use its on()
method to subscribe to EventType.RiveEvent
.
import React, { useEffect } from 'react';
import { useRive, EventType, RiveEvent } from '@rive-app/react-canvas';
const EventListener = () => {
const { rive, RiveComponent } = useRive({
src: 'rating.riv',
stateMachines: 'State Machine 1',
autoplay: true,
});
useEffect(() => {
if (rive) {
const onRiveEvent = (event: RiveEvent) => {
console.log('Rive Event Fired:', event.data);
// event.data contains the name, delay, and any custom properties
const { name, properties } = event.data;
if (name === 'Star Rating') {
console.log('User rated:', properties.rating);
}
};
rive.on(EventType.RiveEvent, onRiveEvent);
// Clean up the event listener on component unmount
return () => {
rive.off(EventType.RiveEvent, onRiveEvent);
};
}
}, [rive]);
return <RiveComponent />;
};
The RiveEvent
Object
When an event is fired, the callback receives a RiveEvent
object. The most important property is data
, which contains:
name
(string
): The name of the event you set in the Rive editor.delay
(number
): The delay in seconds before the event was fired.properties
(object
): An object containing any custom properties you added to the event in the editor.
Automatic Event Handling
For certain types of events (like OpenUrlEvent
), Rive can handle them automatically. For example, if an OpenUrlEvent
is fired, the runtime can automatically open the specified URL in a new tab.
To enable this behavior, set the automaticallyHandleEvents
prop to true
on the <Rive />
component or in the useRive
hook parameters.
// Using the <Rive /> component
<Rive src="..." automaticallyHandleEvents={true} />
// Using the useRive hook
const { RiveComponent } = useRive({
src: '...',
automaticallyHandleEvents: true,
});
By default, this is false
to prevent unexpected side effects. When false
, you must handle all events manually by subscribing to EventType.RiveEvent
.