Getting Started -> Adding Interactivity -> Handle Change Event: use applyNodeChanges and applyEdgeChanges helpers

master
Jason Zhu 2023-05-29 20:01:42 +10:00
parent d93dcdb398
commit 328f950ea6
1 changed files with 27 additions and 4 deletions

View File

@ -1,13 +1,19 @@
import ReactFlow, { Background, Controls } from 'reactflow'; import { useState, useCallback } from 'react';
import ReactFlow, {
Background,
Controls,
applyEdgeChanges,
applyNodeChanges,
} from 'reactflow';
// we have to import the React Flow styles for it to work // we have to import the React Flow styles for it to work
import 'reactflow/dist/style.css'; import 'reactflow/dist/style.css';
const edges = [ const initialEdges = [
{ id: '1-2', source: '1', target: '2', label: 'to the', type: 'step' }, { id: '1-2', source: '1', target: '2', label: 'to the', type: 'step' },
]; ];
const nodes = [ const initialNodes = [
{ {
id: '1', id: '1',
data: { label: 'Hello' }, data: { label: 'Hello' },
@ -22,9 +28,26 @@ const nodes = [
]; ];
const Flow = () => { const Flow = () => {
const [nodes, setNodes] = useState(initialNodes);
const [edges, setEdges] = useState(initialEdges);
const onNodesChange = useCallback(
changes => setNodes(nds => applyNodeChanges(changes, nds)),
[],
);
const onEdgesChange = useCallback(
changes => setEdges(eds => applyEdgeChanges(changes, eds)),
[],
);
return ( return (
<div style={{ height: '100vh' }}> <div style={{ height: '100vh' }}>
<ReactFlow nodes={nodes} edges={edges}> <ReactFlow
nodes={nodes}
onNodesChange={onNodesChange}
edges={edges}
onEdgesChange={onEdgesChange}
>
<Background /> <Background />
<Controls /> <Controls />
</ReactFlow> </ReactFlow>