Skip to content

React Flowのノードを独自コンポーネントで置き換える方法

過去にReact Flowのノードをスタイリングする方法を書いたが、React Flowはノードを独自コンポーネントで置き換えることもできる。このとき、独自のプロパティを渡したいなら data プロパティに設定する。

const nodes = [{
id: `id${i}`,
type: "Link",
data: {
name: "test",
namespace: "example",
},
position: { x: 200, y: 50 },
}]

コンポーネント側は、NodePropsdata プロパティで受け取るが、この型は NodeProps<T> で指定する。

type LinkProps = Readonly<{
name: string;
namespace: string;
}>;
type LinkType = Node<LinkProps>;
function Link({ data }: NodeProps<LinkType>): ReactElement {
return <div>{data.namespace}/{data.name}</div>
}
const nodeTypes: NodeTypes = {
Link: LinkNode,
};
<ReactFlow nodes={nodes} nodeTypes={nodeTypes} fitView />

ノードに配置したリンク要素が押せない

Section titled “ノードに配置したリンク要素が押せない”

正しい方法は分からないけど、selectablefalse の場合は押せなくなるので true にする。

const nodes = [{
...nodeProps,
selectable: true,
}]