How to display images on nodes of a react-d3-graph?

2.3k Views Asked by At

Greetings

I am trying to create a skill/talent-tree like graph with d3+react where each node has an image on it, reacts to hover by displaying a tooltip ( with the description of the skill ), and has a number displayed like an index ( indicating it's level ). Now this is a ( relatively ) complex problem, but my question is related to the first place where I got stuck with this, which is displaying the image on the node.

The code so far:

...
import { Graph } from 'react-d3-graph';
...
const data = {
    nodes: [
        {id:"n1",size: 5, x:160, y:160, label:"1"}, 
        {id:"n2",size: 5, x:120, y:200, label:"2"}, 
        {id:"n3",size: 5, x:200, y:200, label:"3"}, 
        {id:"n4",size: 5, x:280, y:160, label:"4"}, 
        {id:"n5",size: 5, x:240, y:200, label:"5"}, 
        {id:"n6",size: 5, x:320, y:200, label:"6"},
        {id:"n7",size: 5, x:400, y:160, label:"7"},
        {id:"n8",size: 5, x:360, y:200, label:"8"},
        {id:"n9",size: 5, x:440, y:200, label:"9"}
    ],
    links: [
        {id:"e1",source:"n1",target:"n2"},
        {id:"e2",source:"n1",target:"n3"},
        {id:"e3",source:"n1",target:"n4"},
        {id:"e4",source:"n4",target:"n5"},
        {id:"e5",source:"n4",target:"n6"},
        {id:"e6",source:"n4",target:"n7"},
        {id:"e7",source:"n7",target:"n8"},
        {id:"e8",source:"n7",target:"n9"}
    ]
};

const myConfig = {
    nodeHighlightBehavior: true,
    node: {
        color: 'lightgreen',
        size: 120,
        highlightStrokeColor: 'blue'
    },
    link: {
        highlightColor: 'lightblue'
    }
};
...
public render() {
    return ( ...
...
<Graph
                id='graph-id'
                data={data}
                config={myConfig}
                onClickNode={onClickNode}/>

Which displays this: My graph so far

All the solutions for this that I have found are either not using reactjs or not using d3 and I couldn't convert them.

Does anyone know a way of achieving my goal? What should I be using or where can I find legit documentation about this? I could only find extensive docs about js implementations, but not reactjs.

Or alternatively: where and how should I implement the images for the nodes into my existing code?

1

There are 1 best solutions below

0
On

This can now be done via node.viewGenerator which points at a custom component which can contain images or anything you want.

see: https://danielcaldas.github.io/react-d3-graph/docs/index.html#node

ex.

 const  data: GraphData<any, any> = {
        nodes: [],
        links: []
    }
 function generatePersonNode() {
        return <Person />;
    }
 data.nodes.push({ viewGenerator: generatePersonNode });

Where data as a graph prop and Person is a Component.