Search code examples
reactjsd3.js

Simple D3: circles not appending to svg element


I'm trying to render a simple D3 scatterplot - the svg element is present in the DOM but upon inspection the circle elements do not exist in the rendered html. The program compiles successfully. Any hints for a d3 newbie? (I successfully rendered circles by importing a .csv file but am curious as to why declaring the data array of objects here doesn't seem to work as expected.).

import React from 'react';
import * as d3 from 'd3';

const Graph = () => {

  const data = [{ x: 100, y: 200 }, { x: 200, y: 400 }, { x: 300, y: 600 }]; 

  d3.select('svg')
    .selectAll('circle')
    .data(data)
    .enter()
    .append('circle')
    .attr('r', 5)
    .attr('fill', 'blue')
    .attr('cx', d => d['x'])
    .attr('cy', d => d['y']);

  return (
    <>
      <svg id='graph1' width='400' height='800' style={{ background: 'lightgrey' }}/>
    </>
  );
};

export default Graph;```

Solution

  • Looks to me like you need to render the svg BEFORE you append the data?

    d3.select('svg')

    is selecting nothing and therefore appending the data to nothing..