Decouple update logic from useEffect in react+D3 - reactjs

I am trying to build a hierarchical tree visualization using React and D3.
My component receives the hierarchical data in a CSV format as props, which I pass through the stratify function of D3 to obtain a root node to my tree. The root node is set as state.
Currently, I am using a single useEffect(()=>{},[root]) to build the tree, which re-renders on any changes to root.
It is messy as all the action happens inside this useEffect(). I want to know how can I decouple the update() method and use it separately.
As I am a beginner is both React and D3, I welcome any other suggestion on how to handle the state , how to make it more declarative et al.
Here is the code:
useEffect(() => {
if (root) {
//Declare a tree layout
//nodeSize ensure each node has it's own space and does not overlap
const tree = d3
.tree()
.nodeSize([
attributes.nodeWidth,
attributes.nodeHeight + attributes.veritcalNodeGap,
]);
root.x0 = 0;
root.y0 = attributes.width / 2;
//Set children of nodes deeper than 2 to null;
root.descendants().forEach((d, i) => {
d.id = i;
d._children = d.children;
if (d.depth && d.data.child.length !== 7) d.children = null;
});
// append the svg object to the body of the page
// and define zoom behaviours
const svg = d3
.select(d3Ref.current)
.call(
d3
.zoom()
.scaleExtent([0.05, 3])
.on("zoom", () => svg.attr("transform", d3.event.transform))
)
.on("dblclick.zoom", null)
.append("svg")
.attr("viewBox", [0, 0, attributes.width, attributes.height])
.append("g")
.attr("transform", (d) => `translate(${attributes.width / 2},120)`);
//Group all links together
const gLink = svg
.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 1)
.attr("stroke-width", 1.5);
// .attr("x", "200 ");
//Group all nodes together
const gNode = svg
.append("g")
.attr("cursor", "pointer")
.attr("pointer-events", "all");
const diagonal = linkVertical()
.x((d) => d.x)
.y((d) => d.y);
update();
function update() {
const nodes = root.descendants().reverse();
const links = root.links();
tree(root);
//Define group and join the data
const node = gNode.selectAll("g").data(nodes, (d) => d.id);
let nodeEnter = node
.enter()
.append("g")
.attr("class", "node")
.attr("transform", (d) => `translate(${root.x0},${root.y0})`)
.on("click", (d) => {
d.children = d.children ? null : d._children;
update();
});
let nodeGroup = nodeEnter.append("g").attr("class", "node-group");
nodeEnter
.append("circle")
.attr("r", 7)
.attr("cursor", (d) => (d._children ? "pointer" : "none"))
.attr("fill", (d) => (d._children ? "lightsteelblue" : "#999"))
.attr("stroke", (d) => (d._children ? "steelblue" : "#999"))
.attr("stroke-width", 2);
//add text
nodeEnter
.append("text")
.attr("dy", ".35em")
.attr("x", 25)
.text((d) => d.data.child);
//Transition nodes to their new positions
const nodeUpdate = node //SVG.data()
.merge(nodeEnter)
.transition()
.duration(attributes.duration)
.attr("transform", (d) => `translate(${d.x},${d.y})`)
.attr("fill-opacity", 1)
.attr("stroke-opacity", 1);
//Transition exiting nodes to the parent's new position
const nodeExit = node
.exit()
.transition()
.duration(attributes.duration)
.remove()
.attr("transform", (d) => `translate(${root.x},${root.y})`);
// // Update the links…
const link = gLink.selectAll("path").data(links, (d) => d.target.id);
// // Enter any new links at the parent's previous position.
const linkEnter = link
.enter()
.append("path")
.attr("class", "link")
.attr("d", (d) => {
const o = { x: root.x0, y: root.y0 };
return diagonal({ source: o, target: o });
});
// //Transition links to their new position
link
.merge(linkEnter)
.transition()
.duration(attributes.duration)
.attr("d", diagonal);
// // Transition exiting nodes to the parent's new position.
link
.exit()
.transition()
.duration(attributes.duration)
.remove()
.attr("d", (d) => {
const o = { x: root.x, y: root.y };
return diagonal({ source: o, target: o });
});
root.eachBefore((d) => {
d.x0 = d.x;
d.y0 = d.y;
});
}
}
}, [root]);

Here is one idea.
You can have the initial effect onMount once, then updates only when root change,
You can use two useEffect on your component.
// hook on onMount, you prepare root, tree etc
let tree;
useEffect(() => {
if (root) {
//Declare a tree layout
//nodeSize ensure each node has it's own space and does not overlap
tree = d3
.tree()
.nodeSize([
attributes.nodeWidth,
attributes.nodeHeight + attributes.veritcalNodeGap,
]);
root.x0 = 0;
root.y0 = attributes.width / 2;
//Set children of nodes deeper than 2 to null;
root.descendants().forEach((d, i) => {
d.id = i;
d._children = d.children;
if (d.depth && d.data.child.length !== 7) d.children = null;
});
// append the svg object to the body of the page
// and define zoom behaviours
const svg = d3
.select(d3Ref.current)
.call(
d3
.zoom()
.scaleExtent([0.05, 3])
.on('zoom', () => svg.attr('transform', d3.event.transform))
)
.on('dblclick.zoom', null)
.append('svg')
.attr('viewBox', [0, 0, attributes.width, attributes.height])
.append('g')
.attr('transform', (d) => `translate(${attributes.width / 2},120)`);
//Group all links together
const gLink = svg
.append('g')
.attr('fill', 'none')
.attr('stroke', '#555')
.attr('stroke-opacity', 1)
.attr('stroke-width', 1.5);
// .attr("x", "200 ");
//Group all nodes together
const gNode = svg
.append('g')
.attr('cursor', 'pointer')
.attr('pointer-events', 'all');
const diagonal = linkVertical()
.x((d) => d.x)
.y((d) => d.y);
}
}, []);
// here is the update only when [root] changes
useEffect(() => {
const nodes = root.descendants().reverse();
const links = root.links();
tree(root);
//Define group and join the data
const node = gNode.selectAll('g').data(nodes, (d) => d.id);
let nodeEnter = node
.enter()
.append('g')
.attr('class', 'node')
.attr('transform', (d) => `translate(${root.x0},${root.y0})`)
.on('click', (d) => {
d.children = d.children ? null : d._children;
update();
});
let nodeGroup = nodeEnter.append('g').attr('class', 'node-group');
nodeEnter
.append('circle')
.attr('r', 7)
.attr('cursor', (d) => (d._children ? 'pointer' : 'none'))
.attr('fill', (d) => (d._children ? 'lightsteelblue' : '#999'))
.attr('stroke', (d) => (d._children ? 'steelblue' : '#999'))
.attr('stroke-width', 2);
//add text
nodeEnter
.append('text')
.attr('dy', '.35em')
.attr('x', 25)
.text((d) => d.data.child);
//Transition nodes to their new positions
const nodeUpdate = node //SVG.data()
.merge(nodeEnter)
.transition()
.duration(attributes.duration)
.attr('transform', (d) => `translate(${d.x},${d.y})`)
.attr('fill-opacity', 1)
.attr('stroke-opacity', 1);
//Transition exiting nodes to the parent's new position
const nodeExit = node
.exit()
.transition()
.duration(attributes.duration)
.remove()
.attr('transform', (d) => `translate(${root.x},${root.y})`);
// // Update the links…
const link = gLink.selectAll('path').data(links, (d) => d.target.id);
// // Enter any new links at the parent's previous position.
const linkEnter = link
.enter()
.append('path')
.attr('class', 'link')
.attr('d', (d) => {
const o = { x: root.x0, y: root.y0 };
return diagonal({ source: o, target: o });
});
// //Transition links to their new position
link
.merge(linkEnter)
.transition()
.duration(attributes.duration)
.attr('d', diagonal);
// // Transition exiting nodes to the parent's new position.
link
.exit()
.transition()
.duration(attributes.duration)
.remove()
.attr('d', (d) => {
const o = { x: root.x, y: root.y };
return diagonal({ source: o, target: o });
});
root.eachBefore((d) => {
d.x0 = d.x;
d.y0 = d.y;
});
}, [root]);

Related

How to reheat d3 force simulation in React.StrictMode?

I have decided to create a interactive force directed graph in React using D3 but and everything is working for after the simulation started but the dragging doesn't work in React StrictMode I assume it must be due to the mounting and remount of component in ReactStrict mode 18 but I can't really pinpoint the reason.
Where is the content of my use effect hook
useEffect(function () {
if (!svgRef.current) return;
const svg = d3.select(svgRef.current);
const nodes = d3.map(
props.nodes,
(node): Node => ({
...node,
})
);
const links = d3
.map(props.links, (link) => ({
source: nodes.find((node) => node.id === link.source),
target: nodes.find((node) => node.id === link.target),
}))
.filter(
(link): link is { source: Node; target: Node } =>
link.source !== undefined && link.target !== undefined
);
const simulation = d3
.forceSimulation(nodes)
.force(
"link",
d3
.forceLink(links)
.id((_, i) => nodes[i].id)
.distance(LINK_LENGHT)
)
.force("charge", d3.forceManyBody().strength(-NODE_REPULSION))
.force("center", d3.forceCenter())
.force("forceX", d3.forceX().strength(NODE_GRAVITY))
.force("forceY", d3.forceY().strength(NODE_GRAVITY))
.force("colide", d3.forceCollide(NODE_RADIUS * NODE_MARGIN))
.on("tick", ticked);
const link = svg
.selectAll("line")
.data(links)
.enter()
.append("line")
.style("stroke", "#aaa");
const node = svg
.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.call(
d3
.drag<SVGCircleElement, Node>()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
)
.attr("fill", (node) => node.color))
.attr("r", NODE_RADIUS)
.attr("stroke", "#000000")
.attr("stroke-width", 1);
function ticked() {
link
.attr("x1", (d) => d.source.x!)
.attr("y1", (d) => d.source.y!)
.attr("x2", (d) => d.target.x!)
.attr("y2", (d) => d.target.y!);
node.attr("cx", (d) => d.x!).attr("cy", (d) => d.y!);
}
function dragstarted(event: any, d: Node) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event: any, d: Node) {
console.log(simulation.alpha());
d.fx = event.x;
d.fy = event.y;
}
function dragended(event: any, d: Node) {
if (!event.active) simulation.alphaTarget(0.0001);
d.fx = null;
d.fy = null;
}
},
[props.nodes.length, props.links.length]
)
Any clue or help is appreciated.
Due to it working after removing the StrictMode I speculated that i need a cleanup function inside my useEffect. Turns out that i just have to remove the links and nodes that I have inserted like so.
return () => {
node.remove();
link.remove();
}

Create static network graph with D3 in react

I want to generate a static network graph, where the nodes only update the radio atributte and the links changes via props.
const NetworkGraph = props => {
const areaChart = useRef()
const dimensions = {width:400, height:200}
useEffect(() => {
const svg = d3.select(areaChart.current)
.attr('width', dimensions.width)
.attr('height', dimensions.height)
.style('background-color','white')
const nodo = svg
.selectAll("circle")
.data(props.data)
.enter()
.append("circle")
.attr("r", d => d.valor /* Math.floor((Math.random() * 40) + 1) */ )
.style("fill", "#69b3a2")
const link = svg
.selectAll("line")
.data(props.links)
.enter()
.append("line")
.style("stroke", "#aaa")
var simulation = d3.forceSimulation(data.nodes) // Force algorithm is applied to data.nodes
.force("link", d3.forceLink() // This force provides links between nodes
.id(function(d) { return d.id; }) // This provide the id of a node
.links(data.links) // and this the list of links
)
.force("charge", d3.forceManyBody().strength(-500)) // This adds repulsion between nodes. Play with the -400 for the repulsion strength
.force("center", d3.forceCenter(dimensions.width / 2, dimensions.height / 2)) // This force attracts nodes to the center of the svg area
.on("end", ticked);
//.on("tick", () => this.tick());
function ticked() {
link
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
nodo
.attr("cx", function (d) { return d.x+6; })
.attr("cy", function(d) { return d.y-6; });
}
svg.selectAll("*").exit();
}, [props.data]);
return <svg ref={areaChart}> </svg>;
};
export default NetworkGraph;
I tried to use force, but i think i dont have to use it because i have to generate the new incoming graph every 1 second. Here add a image that i want to generate.

D3 + ReactJS network graph hangs the browser indefinitely after continuously updating graph

I am currently learning reactjs and d3 and working on how to visualize the dfs algorithm using network graph. After some iterations of updating the states, the browser hangs and page becomes unresponsive.
I think that I may not be clearing the svg before updating but not getting exactly how to do it.
Below is the renderer code which call the ForceGraph function
import { useEffect, useState } from "react";
import { ForceGraph } from "../forceGraph/forceGraph";
import { Container, Row, Button } from "react-bootstrap";
import "./renderer.css";
import data_dummy from "../../data/dummyGraph.json";
import OptionsButton from "../../components/buttons/optionsButton";
import DFS from "../../algorithms/graphTraversal/dfs";
function GraphOptionTab({
handleStartVisualization,
handleGenerateRandomGraph,
}) {
return (
<Container className="graph_option_container">
<Row className="graph_option_container_row">
<OptionsButton onClick={handleGenerateRandomGraph}>
Random graph
</OptionsButton>
<OptionsButton onClick={handleStartVisualization}>
Start visualization
</OptionsButton>
</Row>
</Container>
);
}
function generateRandomGraph() {
var numberOfNodes = Math.floor(Math.random() * 30);
var nodes = [];
var links = [];
var currentNode = Math.floor(Math.random() * numberOfNodes);
for (var i = 0; i < numberOfNodes; i++) {
var node = {};
node.id = i;
nodes.push({ ...node });
var links_for_each_node = Math.floor(Math.random() * 5);
for (var j = 0; j < links_for_each_node; j++) {
var link = {};
var source = i;
var target = i;
while (source === target) {
target = Math.floor(Math.random() * numberOfNodes);
}
link.source = source;
link.target = target;
link.weight = Math.floor(Math.random() * numberOfNodes);
links.push({ ...link });
}
}
var data = {};
data.nodes = [...nodes];
data.links = [...links];
return data;
}
export default function Renderer() {
const [renderer, setRenderer] = useState("graph");
const [data, setData] = useState(generateRandomGraph());
const [c, setC] = useState(0);
const [isRunning, setIsRunning] = useState(false);
function runAnimation() {
if (data === null) return;
var seq = DFS(data);
console.log(seq);
seq.forEach((a, i) => {
setTimeout(() => {
setData({ ...a });
}, i * 1000 * 2);
});
}
return renderer === "graph" ? (
<Container className="graph_container">
<Row className="graph_container_row1">
<GraphOptionTab
handleGenerateRandomGraph={() => {
setData({ ...generateRandomGraph() });
}}
handleStartVisualization={() => {
if (isRunning) {
runAnimation();
}
setIsRunning(!isRunning);
}}
></GraphOptionTab>
</Row>
<Row className="graph_container_row2">
<ForceGraph data={data}></ForceGraph>
</Row>
</Container>
) : null;
}
ForceGraph
import React from "react";
import { runForceGraph } from "./forceGraphGenerator";
import styles from "./forceGraph.module.css";
export function ForceGraph({ data }) {
const containerRef = React.useRef(null);
React.useEffect(() => {
if (data != null) {
if (containerRef.current) {
const { svg, simulation } = runForceGraph(
containerRef.current,
data.links,
data.nodes,
data.vis,
data.currentNode
);
return function cleanup(destroyFn) {
console.log("Cleanup called");
console.log(simulation);
console.log(svg);
simulation.stop();
svg.selectAll("*").remove();
svg.remove();
};
}
}
});
return <div ref={containerRef} className={styles.container} />;
}
ForceGraphGenerator
import * as d3 from "d3";
import "#fortawesome/fontawesome-free/css/all.min.css";
import styles from "./forceGraph.module.css";
export function runForceGraph(
container,
linksData,
nodesData,
vis,
currentNode
) {
const links = linksData.map((d) => Object.assign({}, d));
const nodes = nodesData.map((d) => Object.assign({}, d));
console.log(`hello current node = ${currentNode}`);
const containerRect = container.getBoundingClientRect();
const height = containerRect.height;
const width = containerRect.width;
const color = () => {
return "#29FF29";
};
const icon = (d) => {
return d.gender === "male" ? "\uf222" : "\uf221";
};
const getClass = (d) => {
return d.gender === "male" ? styles.male : styles.female;
};
const drag = (simulation) => {
const dragstarted = (event, d) => {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
};
const dragged = (event, d) => {
d.fx = event.x;
d.fy = event.y;
};
const dragended = (event, d) => {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
};
return d3
.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
};
const simulation = d3
.forceSimulation(nodes)
.force(
"link",
d3
.forceLink(links)
.id((d) => {
return d.id;
})
.distance(200)
.strength(1)
)
.force("charge", d3.forceManyBody().strength(-1000))
.force("x", d3.forceX())
.force("y", d3.forceY());
simulation.tick(300);
const svg = d3
.select(container)
.append("svg")
.attr("viewBox", [-width / 2, -height / 2, width, height]);
const link = svg
.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 1)
.attr("stroke-width", 2)
.selectAll("line")
.data(links)
.join("line")
.attr("stroke-width", (d) => Math.sqrt(d.value));
const node = svg
.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 2)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 24)
.attr("fill", (d) => {
if (currentNode === d.id) return "#ff3b76";
if (vis && vis[d.id]) return "#fff";
return color();
})
.call(drag(simulation));
const edge_node = svg
.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 2)
.selectAll("circle")
.data(links)
.join("circle")
.attr("r", 8)
.attr("fill", "#fff")
.call(drag(simulation));
const label = svg
.append("g")
.attr("class", "labels")
.selectAll("text")
.data(nodes)
.enter()
.append("text")
.attr("text-anchor", "middle")
.attr("class", styles.node_text)
.attr("dominant-baseline", "central")
.text((d) => {
return d.id;
})
.call(drag(simulation));
const edge_label = svg
.append("g")
.attr("class", "labels")
.selectAll("text")
.data(links)
.enter()
.append("text")
.attr("text-anchor", "middle")
.attr("class", styles.edge_label)
.attr("dominant-baseline", "central")
.text((d) => {
return d.weight;
})
.call(drag(simulation));
simulation.on("tick", () => {
//update link positions
link
.attr("x1", (d) => d.source.x)
.attr("y1", (d) => d.source.y)
.attr("x2", (d) => d.target.x)
.attr("y2", (d) => d.target.y);
// update node positions
node.attr("cx", (d) => d.x).attr("cy", (d) => d.y);
// update label positions
label
.attr("x", (d) => {
return d.x;
})
.attr("y", (d) => {
return d.y;
});
edge_node
.attr("cx", (d) => Math.floor((d.source.x + d.target.x) / 2))
.attr("cy", (d) => Math.floor((d.source.y + d.target.y) / 2));
edge_label
.attr("x", (d) => {
return Math.floor((d.source.x + d.target.x) / 2);
})
.attr("y", (d) => {
return Math.floor((d.source.y + d.target.y) / 2);
});
});
return {
simulation,
svg,
};
}
DFS
vis[v] = true;
var state = {};
state.vis = [...vis];
state.currentNode = v;
state.nodes = data.nodes;
state.links = data.links;
seq.push({ ...state });
adjList[v].forEach((i) => {
if (!vis[i]) {
dfsWrapper(data, adjList, vis, i, seq);
}
});
}
export default function DFS(data) {
var seq = [];
var numberOfNodes = data.nodes.length;
var vis = new Array(numberOfNodes).fill(false);
var adjList = new Array(numberOfNodes);
for (var i = 0; i < adjList.length; i++) {
adjList[i] = new Array();
}
console.log(data.links);
for (var i = 0; i < data.links.length; i++) {
// console.log(data.links[i]["source"]);
adjList[data.links[i]["source"]].push(data.links[i]["target"]);
// console.log(adjList[data.links[i]["source"]]);
}
console.log(adjList);
for (var i = 0; i < numberOfNodes; i++) {
if (!vis[i]) {
dfsWrapper(data, adjList, vis, data.nodes[i].id, seq);
}
}
var state = {};
state.vis = [...vis];
state.currentNode = numberOfNodes + 1;
state.nodes = data.nodes;
state.links = data.links;
seq.push({ ...state });
return seq;
}
Hope that my question is clear and it would be very kind if anyone suggest what is going wrong.
Try to split runForceGraph into 2 functions: createForceGraph and updateForceGraph
Call createForceGraph once when you mount your component:
export function createForceGraph(...) {
...
const svg = d3
.select(container)
.append("svg")
...
svg
.append("g")
.attr("class", "labels")
...
}
Call updateForceGraph each time the data is changed:
export function updateForceGraph(...) {
...
const edge_label = d3
.select('.labels')
.selectAll("text")
.data(links)
.enter()
...

How to remove the previous instance from ReactJS through D3?

I would like to draw new treemap every time the data (data is generated based on the user interaction such as button clicks) is changed. At the moment every time the data is changed a new treemap is created but it is drawn on top of the previous treemap - meaning I can see both treemaps on the screen. Somehow the previous instance is not removed.
I have looked at this and this, and applied remove() function to remove the previous instance via d3. However, it does not work. I may be incorrectly used the remove function in the life cycle.
d3.select("treemap").remove(); is used in the second useEffect method.
export function Treemap({ width, height, data }) {
const ref = useRef();
useEffect(() => {
const svg = d3
.select(ref.current)
.attr("id", "treemap")
.attr("width", width)
.attr("height", height);
}, []);
useEffect(() => {
//THIS IS WHERE I USE REMOVE FUNCTION;
d3.select("treemap").remove();
draw();
}, [data]);
const draw = () => {
const svg = d3.select(ref.current);
// Give the data to this cluster layout:
var root = d3.hierarchy(data).sum(function (d) {
return d.value;
});
// initialize treemap
d3
.treemap()
.size([width, height])
.paddingTop(28)
.paddingLeft(0)
.paddingRight(0)
.paddingBottom(7)
.paddingInner(3)(root);
const color = d3
.scaleOrdinal()
.domain(["Diary", "Sweetner", "Fruit"])
.range(["#8FD175", "#402D54", "#E67E22"]);
const opacity = d3.scaleLinear().domain([10, 30]).range([0.5, 1]);
// Select the nodes
var nodes = svg.selectAll("rect").data(root.leaves());
// draw rectangles
nodes
.enter()
.append("rect")
.attr("x", function (d) {
return d.x0;
})
.attr("y", function (d) {
return d.y0;
})
.attr("width", function (d) {
return d.x1 - d.x0;
})
.attr("height", function (d) {
return d.y1 - d.y0;
})
.style("stroke", "black")
.style("fill", function (d) {
return color(d.parent.data.name);
})
.style("opacity", function (d) {
return opacity(d.data.value);
});
nodes.exit().remove();
// select node titles
var nodeText = svg.selectAll("text").data(root.leaves());
// add the text
nodeText
.enter()
.append("text")
.attr("x", function (d) {
return d.x0 + 5;
}) // +10 to adjust position (more right)
.attr("y", function (d) {
return d.y0 + 20;
}) // +20 to adjust position (lower)
.text(function (d) {
return d.data.name;
})
.attr("font-size", "19px")
.attr("fill", "white");
// select node titles
var nodeVals = svg.selectAll("vals").data(root.leaves());
// add the values
nodeVals
.enter()
.append("text")
.attr("x", function (d) {
return d.x0 + 5;
}) // +10 to adjust position (more right)
.attr("y", function (d) {
return d.y0 + 35;
}) // +20 to adjust position (lower)
.text(function (d) {
return d.data.value;
})
.attr("font-size", "11px")
.attr("fill", "white");
// add the parent node titles
svg
.selectAll("titles")
.data(
root.descendants().filter(function (d) {
return d.depth == 1;
})
)
.enter()
.append("text")
.attr("x", function (d) {
return d.x0;
})
.attr("y", function (d) {
return d.y0 + 21;
})
.text(function (d) {
return d.data.name;
})
.attr("font-size", "19px")
.attr("fill", function (d) {
return color(d.data.name);
});
};
return (
<div className="chart">
<svg ref={ref}></svg>
</div>
);
}
Normally, with d3, you never remove the already drawn nodes. It's much cheaper (computationally) and easier to just repurpose them!
If you really want to remove all nodes, d3.select("treemap") doesn't do anything, because "treemap" is not a valid selector. Try #treemap instead.
Or, if you want to repurpose the already drawn bits, consider the following:
function Treemap({
width,
height
}) {
const ref = React.useRef();
const [data, setData] = React.useState(`
{
"name": "Fruit",
"children": [
{ "name": "Apples", "value": 1 },
{ "name": "Oranges", "value": 1 },
{ "name": "Bananas", "value": 1 }
]
}
`);
React.useEffect(() => {
const svg = d3
.select(ref.current)
.attr("id", "treemap")
.attr("width", width)
.attr("height", height);
}, []);
React.useEffect(() => {
draw();
}, [data]);
const draw = () => {
const svg = d3.select(ref.current);
let parsedData
try {
parsedData = JSON.parse(data);
} catch (e) {
console.log(e);
return;
}
// Give the data to this cluster layout:
var root = d3.hierarchy(parsedData).sum(function(d) {
return d.value;
});
// initialize treemap
d3
.treemap()
.size([width, height])
.paddingTop(28)
.paddingLeft(0)
.paddingRight(0)
.paddingBottom(7)
.paddingInner(3)(root);
const color = d3
.scaleOrdinal()
.domain(["Diary", "Sweetner", "Fruit"])
.range(["#8FD175", "#402D54", "#E67E22"]);
const opacity = d3.scaleLinear().domain([10, 30]).range([0.5, 1]);
// Select the nodes
var nodes = svg.selectAll("rect").data(root.leaves());
// draw rectangles
var newNodes = nodes
.enter()
.append("rect")
.style("stroke", "black");
nodes.merge(newNodes)
.attr("x", function(d) {
return d.x0;
})
.attr("y", function(d) {
return d.y0;
})
.attr("width", function(d) {
return d.x1 - d.x0;
})
.attr("height", function(d) {
return d.y1 - d.y0;
})
.style("fill", function(d) {
return color(d.parent.data.name);
})
.style("opacity", function(d) {
return opacity(d.data.value);
});
nodes.exit().remove();
// select node titles
var nodeVals = svg.selectAll(".val").data(root.leaves());
nodeVals.exit().remove();
// add the values
var newNodeVals = nodeVals
.enter()
.append("text")
.classed("val", true)
.attr("font-size", "11px")
.attr("fill", "white");
nodeVals.merge(newNodeVals)
.attr("x", function(d) {
return d.x0 + 5;
}) // +10 to adjust position (more right)
.attr("y", function(d) {
return d.y0 + 35;
}) // +20 to adjust position (lower)
.text(function(d) {
return d.data.value;
});
// add the parent node titles
var titles = svg
.selectAll(".title")
.data(
root.descendants().filter(function(d) {
return d.depth == 1;
})
);
titles.exit().remove();
var newTitles = titles
.enter()
.append("text")
.classed("title", true)
.attr("font-size", "19px");
titles.merge(newTitles)
.attr("x", function(d) {
return d.x0 + 5;
})
.attr("y", function(d) {
return d.y0 + 21;
})
.text(function(d) {
return d.data.name;
})
.attr("fill", function(d) {
return color(d.data.name);
});
};
return ( <
div className = "chart" >
<
textarea onChange = {
(el) => setData(el.target.value)
}
value = {
data
}
rows = "20"
cols = "50" / >
<
svg ref = {
ref
} > < /svg> <
/div>
);
}
ReactDOM.render( <
Treemap width = "600"
height = "300" / > ,
document.getElementById('root')
)
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.js"></script>
<div id="root"></div>
In any case, all your selectors were missing the .-class prefix. I'd recommend to read up on selectors, and on the enter(), exit(), merge() lifecycle.

React + D3 + Force-Directed Tree + Adjustable Link Strength

I'm trying to make Force-Directed Tree with React and it works. But I cannot modify "link strength", if I pass it outside component through the props.
Honestly, I can change "strength", but I need to append d3 svg to my react ref div after that to see the changes. And whole graph will be redrawn.
I find example by Mike Bostock. He advice to modify the parameters of a force-directed graph with reheat the simulation using simulation.alpha and simulation.restart. But I cannot make it works with react. Nothing happens.
Here is my code:
export default function Hierarchy(props) {
const {
strength,
lineColor,
lineStroke,
width,
height,
nodeSize,
nodeColor,
} = props;
const root = d3.hierarchy(data);
const links = root.links();
const nodes = root.descendants();
const svg = d3.create("svg");
const link = svg
.append("g")
.selectAll("line")
.data(links)
.join("line");
const node = svg
.append("g")
.selectAll("circle")
.data(nodes)
.join("circle");
function applyStyle(selectionSVG) {
selectionSVG
.attr("width", width)
.attr("height", height)
.attr("viewBox", [-width / 2, -height / 2, width, height]);
selectionSVG
.selectAll("circle")
.attr("r", nodeSize)
.attr("fill", nodeColor)
selectionSVG
.selectAll("line")
.attr("stroke", lineColor)
.attr("stroke-width", lineStroke);
}
applyStyle(svg);
const divRef = React.useRef(null);
const linkForce = d3
.forceLink(links)
.id(d => d.id)
.distance(0)
.strength(strength);
const simulation = d3
.forceSimulation(nodes)
.force("link", linkForce)
.force("charge", d3.forceManyBody().strength(-500))
.force("x", d3.forceX())
.force("y", d3.forceY());
simulation.on("tick", () => {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node.attr("cx", d => d.x).attr("cy", d => d.y);
});
//ComponentDidMount
useEffect(() => {
//Append d3 svg to ref div
var div = d3.select(divRef.current);
if (div.node().firstChild) {
div.node().removeChild(div.node().firstChild);
}
div.node().appendChild(svg.node());
}, []);
//ComponentDidUpdate
useEffect(() => {
simulation.force("link").strength(strength);
simulation.alpha(1).restart();
}, [strength]);
//ComponentDidUpdate
useEffect(() => {
var div = d3.select(divRef.current);
applyStyle(div.select("svg"));
});
//Render
return <div id="hierarchyTree" ref={divRef} />;
}
Here is Sandbox.
I find solution, if anybody interesting.
The fact is simulation was not saved when component was updated. So I create ref for it.
const simulationRef = React.useRef(simulation)
and replace it in useEffect section
//ComponentDidUpdate
useEffect(() => {
simulationRef.current.force("link").strength(strength)
simulationRef.current.alpha(1).restart()
console.log(simulationRef.current)
}, [strength])
After that everything works fine.

Resources