javascriptreactjsreact-flow

Reactflow - Background displaying over nodes


Using reactflow, on a simple graph I am trying to use the <Background/> Reactflow component as follows :

import React, { useCallback, useState } from 'react';
import ReactFlow, {
    addEdge,
    FitViewOptions,
    applyNodeChanges,
    applyEdgeChanges,
    Node,
    Edge,
    NodeChange,
    EdgeChange,
    Connection,
    Background,
    BackgroundVariant,
} from 'reactflow';

interface CreateGraphProps {

}

const initialNodes: Node[] = [
    { id: '1', data: { label: 'Node 1' }, position: { x: 5, y: 5 } },
    { id: '2', data: { label: 'Node 2' }, position: { x: 5, y: 100 } },
];

const initialEdges: Edge[] = [{ id: 'e1-2', source: '1', target: '2' }];

const fitViewOptions: FitViewOptions = {
    padding: 0.2,
};

export const CreateGraph: React.FC<CreateGraphProps> = ({ }) => {
    const [nodes, setNodes] = useState<Node[]>(initialNodes);
    const [edges, setEdges] = useState<Edge[]>(initialEdges);

    const onNodesChange = useCallback(
        (changes: NodeChange[]) => setNodes((nds) => applyNodeChanges(changes, nds)),
        [setNodes]
    );
    const onEdgesChange = useCallback(
        (changes: EdgeChange[]) => setEdges((eds) => applyEdgeChanges(changes, eds)),
        [setEdges]
    );
    const onConnect = useCallback(
        (connection: Connection) => setEdges((eds) => addEdge(connection, eds)),
        [setEdges]
    );

    return (
        <div>
            <ReactFlow
                nodes={nodes}
                edges={edges}
                onNodesChange={onNodesChange}
                onEdgesChange={onEdgesChange}
                onConnect={onConnect}
                attributionPosition='bottom-right'
                fitView
                fitViewOptions={fitViewOptions}>
                    <Background color='#a6a6a6' variant={'dots' as BackgroundVariant}/>
            </ReactFlow>

        </div>

    );
}

Without the background, the OnConnect, onEdgesChanges and onNodesChange functions work well. However, with the background it is not the case. The nodes can't be moved when the Background component is present.

Upon further investigation it seems that the background component is placed above the reactflow canvas. Is there somthing missing, prohibiting it from functionning properly?


Solution

  • I have found an answer that works for me, to get theming to work you need to import:

    import 'reactflow/dist/style.css';
    

    This can be used as a base theme to get started. Docs are here.