Skip to main content
Version: 4.3

useOnGraphEvents()

On the current graph​

function useOnGraphEvents(handlers): void;

Subscribes to graph events by their native JointJS names, so you can react to cells being added, removed, moved, or otherwise changed without wiring up listeners by hand. This form reads the graph from the surrounding <GraphProvider> and throws when used outside one.

Handlers are always-latest: the subscription is established once and each event reads the current handler, so inline maps and closures need no useCallback. Re-subscription happens only when the graph or the set of event names changes.

See GraphEventMap for the available event names and their arguments.

Parameters​

ParameterTypeDescription
handlersGraphEventMapMap of JointJS graph event names to callbacks.

Returns​

void

Example​

import { GraphProvider, useOnGraphEvents } from '@joint/react';

function CellLogger() {
useOnGraphEvents({
add: (cell) => console.log('added', cell.id),
remove: (cell) => console.log('removed', cell.id),
'change:position': (cell) => console.log('moved', cell.id),
});
return null;
}

// Mount inside a <GraphProvider> so the hook can find the graph.
<GraphProvider>
<CellLogger />
</GraphProvider>

On a specific graph​

function useOnGraphEvents(graph, handlers): void;

Subscribes to graph events on a graph instance you pass in explicitly. Reach for this when you hold a dia.Graph outside of any <GraphProvider> (e.g. a graph you created yourself). Same always-latest handler semantics as the context form.

Parameters​

ParameterTypeDescription
graphGraphThe graph instance to listen on.
handlersGraphEventMapMap of JointJS graph event names to callbacks.

Returns​

void

Example​

import { dia } from '@joint/core';
import { useOnGraphEvents } from '@joint/react';

function useGraphLogger(graph: dia.Graph) {
useOnGraphEvents(graph, {
add: (cell) => console.log('added', cell.id),
});
}