0

I'm using 'reactflow' library in my react project I'm trying to find a way to use an image in place of node so i can drag and move the image i want and also connect two images via edges I have gone through the docs of reactflow but didn't find a solution I don't know if its supported by library or not Looking forward for any help.

Burhan Ali
  • 49
  • 5

1 Answers1

1

It is supported by the React Flow because React Flow's "custom nodes are just React components, you can implement anything you need".

You can create a custom node with a div as the node and then set the background-image of the div, via CSS, with whatever you'd like. (Alternatively, you can use an img element and set the src property.)

background-image example:

import React, { memo } from "react";
import { Handle, Position } from "reactflow";

export default memo(({ data, isConnectable }) => {
  return (
    <>
      <Handle
        type="target"
        position={Position.Left}
        isConnectable={isConnectable}
      />
      <div
        style={{
          height: data.image.height,
          width: data.image.width,
          backgroundImage: `url(${data.image.url})`,
          backgroundRepeat: "no-repeat"
        }}
      />
      <Handle
        type="source"
        position={Position.Right}
        id="a"
        isConnectable={isConnectable}
      />
    </>
  );
});

Working CodeSandbox: https://codesandbox.io/s/react-flow-image-node-92kxwn?file=/ImageNode.js:0-789

Or

<img /> example:

import React, { memo } from "react";
import { Handle, Position } from "reactflow";

export default memo(({ data, isConnectable }) => {
  return (
    <>
      <Handle
        type="target"
        position={Position.Left}
        onConnect={(params) => console.log("handle onConnect", params)}
        isConnectable={isConnectable}
      />
      <img src={data.image.url} alt={data.image.alt} />
      <Handle
        type="source"
        position={Position.Right}
        id="a"
        isConnectable={isConnectable}
      />
    </>
  );
});

Working CodeSandbox: https://codesandbox.io/s/react-flow-image-node-img-nrt2xy?file=/ImageNode.js

Both examples produce the following output:

custom image node example output

Steve
  • 11,596
  • 7
  • 39
  • 53