useOnSelectionChange
Source on GitHub (opens in a new tab)
This hook lets you listen for changes to both node and edge selection. As the name implies, the callback you provide will be called whenever the selection of either nodes or edges changes.
You need to memoize the passed onChange
handler, otherwise the hook will not
work correctly.
import { useState, useCallback } from 'react';
import ReactFlow, { useOnSelectionChange } from 'reactflow';
function SelectionDisplay() {
const [selectedNodes, setSelectedNodes] = useState([]);
const [selectedEdges, setSelectedEdges] = useState([]);
// the passed handler has to be memoized, otherwise the hook will not work correctly
const onChange = useCallback(({ nodes, edges }) => {
setSelectedNodes(nodes.map((node) => node.id));
setSelectedEdges(edges.map((edge) => edge.id));
}, [])
useOnSelectionChange({
onChange
});
return (
<div>
<p>Selected nodes: {selectedNodes.join(', ')}</p>
<p>Selected edges: {selectedEdges.join(', ')}</p>
</div>
);
}
Signature
Name | Type |
---|---|
#Params |
|
# options | object |
# options.onChange | |
#Returns |
|
void |
Notes
- This hook can only be used in a component that is a child of a
<ReactFlowProvider />
or a<ReactFlow />
component.