Setting Up Data Binding
To use the Data Binding features, you must use the @rive-app/react-webgl2
package. The setup involves a few key hooks to get a reference to a specific ViewModelInstance
.
npm install @rive-app/react-webgl2
The Setup Flow
Here is the standard sequence for setting up data binding in a component:
useRive
: Initialize Rive, making sure to setautoBind: false
. This prevents the default State Machine from binding automatically, allowing you to bind a ViewModelInstance instead.useViewModel
: Get a reference to theViewModel
definition from the loaded Rive file by its name.useViewModelInstance
: Get a live, usableViewModelInstance
from theViewModel
.- Property Hooks: Use hooks like
useViewModelInstanceString
to interact with the properties of your instance.
Example: Stocks Dashboard Setup
Let's look at the setup from the Stocks Dashboard example, which has a ViewModel named "Dashboard"
.
import React, { useEffect } from 'react';
import {
useRive,
useViewModel,
useViewModelInstance,
useViewModelInstanceString,
} from '@rive-app/react-webgl2';
const StocksDashboard = () => {
// 1. Initialize useRive with autoBind: false
const { rive, RiveComponent } = useRive({
src: 'stocks.riv',
artboard: 'Main',
stateMachines: 'State Machine 1',
autoplay: true,
autoBind: false, // Important!
});
// 2. Get the ViewModel definition by name
const viewModel = useViewModel(rive, { name: 'Dashboard' });
// 3. Get the default instance of the ViewModel and bind it to the Rive instance
const viewModelInstance = useViewModelInstance(viewModel, { rive });
// 4. Now you can use property hooks with the instance
const { setValue: setTitle } = useViewModelInstanceString(
'title',
viewModelInstance
);
useEffect(() => {
if (setTitle) {
setTitle('Rive Stocks Dashboard');
}
}, [setTitle]);
return <RiveComponent />;
};
ViewModel Instances
The useViewModelInstance
hook allows you to work with either the default instance or named instances that you create in the Rive editor.
-
Default Instance:
// Gets the default instance const instance = useViewModelInstance(viewModel, { rive });
-
Named Instance: If you have multiple instances of a ViewModel (e.g., for a list of items), you can get them by name.
// Gets the instance named 'Steve' const steveInstance = useViewModelInstance(viewModel, { name: 'Steve', rive });
Once you have your viewModelInstance
, you can proceed to read and write its properties using the specific hooks covered in the Properties Guide.