MENU
Using Backbone Models in Components
The simplest way to consume Backbone models and collections from a React component is to force an update. Components responsible for rendering models would listen to 'change' events, while components responsible for rendering collections would listen for 'add' and 'remove' events.
import React, { useReducer, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import Backbone from 'backbone';
function useForceUpdate() {
const [, forceRender] = useReducer(x => x + 1, 0);
return forceRender;
}
function Item({ model }) {
const forceUpdate = useForceUpdate();
useEffect(() => {
model.on('change', forceUpdate);
return () => model.off('change', forceUpdate);
}, [model, forceUpdate]);
return <li>{model.get('text')}</li>;
}
function List({ collection }) {
const forceUpdate = useForceUpdate();
useEffect(() => {
collection.on('add remove', forceUpdate);
return () => collection.off('add remove', forceUpdate);
}, [collection, forceUpdate]);
return (
<ul>
{collection.map(model => (
<Item key={model.cid} model={model} />
))}
</ul>
);
}
const collection = new Backbone.Collection([
new Backbone.Model({ text: 'A' }),
new Backbone.Model({ text: 'B' }),
new Backbone.Model({ text: 'C' }),
]);
const root = createRoot(document.getElementById('root'));
root.render(<List collection={collection} />);