Change react-flow edge color to gradient.

Vaibhav Rai
2 min readNov 15, 2022

--

I came across a issue where I wanted to change the edge color to some gradient color and after going through the API Docs of the Custom Edges API I realised that behind the hood react-flow create a svg and pass the stroke property to its path and to achieve a gradient color I will need a svg gradient element in the dom.

So we need two things :

- gradient svg element in the dom
- stroke of react-flow edge to be same as a svg gradient

We can create a different resusable component which contain the edge gradient element i.e.

export default function GradientEdge() {
return (
<svg viewBox="0 0 10 10" style={{ height: 0, width: 0 }}>
<defs>
<linearGradient id="edgegradient" gradientTransform="rotate(90)">
<stop offset="5%" stop-color="gold" />
<stop offset="95%" stop-color="red" />
</linearGradient>
</defs>

<circle cx="5" cy="5" r="4" fill="url('#myGradient')" />
</svg>
);
}

Things to notice here is the style on the svg where height and width is both set to 0 and reason is we want this element to be registered in the dom but only for its gradient part.

Now if we go to the example mention here https://reactflow.dev/docs/examples/edges/custom-edge/ we can see that that the color of the edge is set using the svg stroke property, we just change any of the stroke property to url(#<linearGradient-element-id>) i.e.,

  {
id: "edges-e3-5",
source: "edges-4",
target: "edges-5",
style: { stroke: "url(#edgegradient)" }
},

And thats all, for a working example kindly check this example
https://codesandbox.io/s/interesting-dan-i9j8eg?file=/App.js:1943-2063

--

--

No responses yet