Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda