Skip to Content

2024-06-11

Layouting example for Entitree Flex

Hayleigh Thompson
Software Engineer

We add a new layouting algorithm to our example lineup with the addition of Entitree Flex. This algorithm is similar to d3-hierarchy but allows for sibling nodes as well as nodes with different dimensions.

This example was very kindly contributed by GitHub user @kaustubhxd , thanks Kaustubh! Check it out below.

import React, { useCallback } from 'react'; import { Background, ReactFlow, addEdge, ConnectionLineType, Panel, useNodesState, useEdgesState, } from '@xyflow/react'; import '@xyflow/react/dist/style.css'; import CustomNode from './CustomNode'; import { initialTree, treeRootId } from './initialElements'; import { layoutElements } from './layout-elements'; const nodeTypes = { custom: CustomNode, }; const { nodes: layoutedNodes, edges: layoutedEdges } = layoutElements( initialTree, treeRootId, 'TB', ); const LayoutFlow = () => { const [nodes, setNodes, onNodesChange] = useNodesState(layoutedNodes); const [edges, setEdges, onEdgesChange] = useEdgesState(layoutedEdges); const onConnect = useCallback( (params) => setEdges((eds) => addEdge({ ...params, type: ConnectionLineType.SmoothStep, animated: true }, eds), ), [], ); const onLayout = useCallback( (direction) => { const { nodes: layoutedNodes, edges: layoutedEdges } = layoutElements( initialTree, treeRootId, direction, ); setNodes([...layoutedNodes]); setEdges([...layoutedEdges]); }, [nodes, edges], ); return ( <ReactFlow nodes={nodes} edges={edges} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={onConnect} connectionLineType={ConnectionLineType.SmoothStep} fitView nodeTypes={nodeTypes} > <Panel position="top-right"> <button className="xy-theme__button" onClick={() => onLayout('TB')}> vertical layout </button> <button className="xy-theme__button" onClick={() => onLayout('LR')}> horizontal layout </button> </Panel> <Background /> </ReactFlow> ); }; export default LayoutFlow;

Get Pro examples, prioritized bug reports, 1:1 support from the maintainers, and more with React Flow Pro

Last updated on