Programmatically changing Node dimensions in React Flow
-
Changing a node’s dimensions sounds simple. But doing it consistently in React Flow isn’t so straightforward.
When you look at the
Node
type, you’ll noticewidth
andheight
attributes. It might seem like you can just update those. But according to the React Flow docs, those values are read-only. The same goes formeasured: { width: number; height: number }
.So how do you actually change a node’s dimensions?
The React Flow team recommends using CSS. From the docs:
“You shouldn’t try to set the width or height of a node directly. It is calculated internally by React Flow and used when rendering the node in the viewport. To control a node’s size you should use the style or className props to apply CSS styles instead.”
That usually works. But there’s a catch.
If you want a consistent way to both set and get a node’s dimensions, relying on the
style
prop might not be enough. Why? Because of theNodeResizer
component.NodeResizer
lets users resize nodes manually using UI handles. But when they do, React Flow doesn't update thestyle
prop. Instead, it directly modifies thewidth
andheight
attributes using internal state changes.If you look at how
NodeResizer
works under the hood, you’ll see that React Flow uses aNodeDimensionChange
to update the node’s size.So how can you trigger that same kind of change programmatically using only official React Flow methods?
Use
applyNodeChanges
from the React Flow API:const customDimensionsChange: NodeDimensionChange = { id: 'node-1', type: 'dimensions', dimensions: { width: 300, height: 200 }, setAttributes: true, }; setNodes((nodes) => applyNodeChanges([customDimensionsChange], nodes));
This updates the
width
andheight
attributes properly. It’s the most consistent way to change node dimensions programatically in React Flow.