I have created a basic D3 svg just to test some things out with react. For reference, here is my code:
App.js
import './App.css';
import Graph from './Graph/Graph';
function App() {
return (
<Graph />
);
}
export default App;
Graph.js
import * as d3 from "d3"
function Graph(props) {
let svg = d3.select("svg")
svg.append('rect')
.attr("height", 10)
.attr("width", 10)
.style("fill", "Green");
return (
<div>
<svg id="svgID" width="640" height="480"></svg>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="index.js"></script>
</div>
)
}
export default Graph
The issue I am having is where it loads the green rectangle only sometimes, I don't seem to have control over when it loads and when it doesn't.
I think it might be because the SVG is being returned before it has time to append anything to it, however, I am unsure of a fix. Any help?
You need to take a reference of your svg DOM element which persists between renders. The React API gives you the useRef to do that with functional component (see docs).
To bind a DOM Element with a reference, you need to use the ref JSX arrtibute.
<svg ref={svgRef} id="svgID" width="640" height="480"></svg>
Since useRef doesn't tell when it is binded with the DOM element, you need to couple the "ref" returned with useEffect hook to check when current is binded with the svg DOM element.
import React, { useRef, useEffect } from 'react'
import * as d3 from "d3"
function Graph(props) {
const svgRef = useRef(null);
useEffect(
() => {
// Check that svg element has been rendered
if(svg.current) {
let svg = d3.select(svgRef.current)
svg.append('rect')
.attr("height", 10)
.attr("width", 10)
.style("fill", "Green");
}
}
},[svgRef.current])
return (
<div>
<svg ref={svgRef} id="svgID" width="640" height="480"></svg>
</div>
)
}
export default Graph