Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
D3.js SVG object not showing every time I run react project

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!