Search code examples
javascriptreactjsgraphvizreact-graph-vis

can we change the color of node in react + graph


I am using the below package. I have the first and last node. I want to change its background color.

nodes: [
      { id: 'Node 1', label: "Node 1", title: "node 1 tootip text" ,first:true},
      { id: 2, label: "Node 2", title: "node 2 tootip text" },
      { id: 3, label: "Node 3", title: "node 3 tootip text" },
      { id: 4, label: "Node 4", title: "node 4 tootip text" },
      { id: 5, label: "Node 5", title: "node 5 tootip text",last:true }
    ],

first node have first:true and last:true. can we change their background color ?? like red and green https://www.npmjs.com/package/react-graph-vis

here is my code https://stackblitz.com/edit/react-yvpt5j


Solution

  • Just add color property

    Working Demo

     const graph = {
        nodes: [
          { id: 'Node 1', label: "Node 1", title: "node 1 tootip text" ,first:true,  color: "red" },
          { id: 2, label: "Node 2", title: "node 2 tootip text" },
          { id: 3, label: "Node 3", title: "node 3 tootip text" },
          { id: 4, label: "Node 4", title: "node 4 tootip text" },
          { id: 5, label: "Node 5", title: "node 5 tootip text",last:true, color: 'Green' }
        ],
        edges: [
          { from: 'Node 1', to: 2,label:'dddddd' },
          { from: 'Node 1', to: 3,label:'adasd' },
          { from: 2, to: 4 },
          { from: 2, to: 5 }
        ]
      };
    

    or you can change it dynamically on the basic of first and last properties

        let obj = { nodes: [
              { id: 'Node 1', label: "Node 1", title: "node 1 tootip text" ,first:true},
              { id: 2, label: "Node 2", title: "node 2 tootip text" },
              { id: 3, label: "Node 3", title: "node 3 tootip text" },
              { id: 4, label: "Node 4", title: "node 4 tootip text" },
              { id: 5, label: "Node 5", title: "node 5 tootip text",last:true }
            ] };
        
        let updatedNodes = obj.nodes.map(( o ) => {
        	let {first, last} = o;
        	first ? o.color = 'red' : last ? o.color = 'green' : null;
        	return {...o}
        });
        console.log(updatedNodes);