Complex Example
In this more complex example we will be wrapping reactflow
a library for building node based applications like flow charts, diagrams, graphs, etc.
Import
Lets start by importing the library reactflow. Lets make a seperate file called reactflow.py
and add the following code:
Notice we also use the _get_custom_code
method to import the css file that is needed for the styling of the library.
Components
For this tutorial we will wrap three components from Reactflow: ReactFlow
, Background
, and Controls
. Lets start with the ReactFlow
component.
Here we will define the tag
and the vars
that we will need to use the component.
For this tutorial we will define EventHandler
props on_nodes_change
and on_connect
, but you can find all the events that the component triggers in the reactflow docs.
Now lets add the Background
and Controls
components. We will also create the components using the create
method so that we can use them in our app.
Building the App
Now that we have our components lets build the app.
Lets start by defining the initial nodes and edges that we will use in our app.
Next we will define the state of our app. We have four event handlers: add_random_node
, clear_graph
, on_connect
and on_nodes_change
.
The on_nodes_change
event handler is triggered when a node is selected and dragged. This function is used to update the position of a node during dragging. It takes a single argument node_changes
, which is a list of dictionaries containing various types of metadata. For updating positions, the function specifically processes changes of type position
.
Now lets define the UI of our app. We will use the react_flow
component and pass in the nodes
and edges
from our state. We will also add the on_connect
event handler to the react_flow
component to handle when an edge is connected.
Here is an example of the app running: