I have tried different ways of implementing this beauty, but it doesn't seem to work. My problem is that when I hit the button, I want to change the layout of the graph, which happens and I am glad for it, but I also want my graph to be centered (fit) on the screen. The first button click changes the direction, but doesn't fit the instance. To fit the instance I need to hit the button for a second time. I guess it has to do with asynchronous JS or? This is my code:

  const onChangeTreeLayout = useCallback(
    (treeLayoutDirection) => {
      const layoutedElements = getLayoutedGraphElements(
        elements,
        treeLayoutDirection,
        setTreeLayoutDirection
      );
      setElements(layoutedElements);
    },
    [elements]
  );

Then how I get the instance and trigger it follows: Note: I can't use useReactFlow() hook as we decided not to migrate to a newer version. But useZoomPanHelper does its work anyway.

const reactFlowInstance = useZoomPanHelper();
<button
   onClick={() => {
     onChangeTreeLayout('TB');
     reactFlowInstance.fitView();
   }}
>
  Horizontal Layout
</button>

I have also tried putting the function .fitView() inside the onChangeTreeLayout but I get the same behaviour.

1

There are 1 best solutions below

0
On

I think calling fitView() with setting new elements will affect just like setting a state and using that state variable in the same function. fitView() should be called after rerendering the new elements.

You could try setTimeout(reactFlowInstance.fitView)