0

I'm trying to make a simple line chart with d3.js, React and PatternFly 4. I have made other graphs who works as intented with the select id, but this one refuses to work and I can't put my finger on the issue.

Note that the id is already created when this class is called, so it exists when the select occurs.

render() {

### This only works if I replace "#linechart" by "body"
var svg = d3.select("#linechart").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform",
            "translate(" + margin.left + "," + margin.top + ")");

x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);
svg.append("path")
        .data([data])
        .attr("class", "line")
        .attr("d", valueline);

svg.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

svg.append("g")
        .call(d3.axisLeft(y));
return ( 
   <div id={"#" + this.props.id}></div>
);

I'm quite the noob in d3.js right now, this code is pretty much a copy paste from an example online with a few ajustements.

  • 1
    Put this at the start: `console.log(d3.select('#linechart').size())` – Coderino Javarino May 24 '19 at 17:08
  • Returns 1. I've made it work using createRef() from React, but I'd still like to know what was going on here. – Dave Berthiaume May 24 '19 at 17:57
  • 1
    I always put my d3 code in the componentDidMount section, not the render section. That way anything you want in the DOM, defined in the render section, is already there by the time d3 hits it. Makes it easier to organize your code this way too. I realize this doesn't answer your question (unless the id of your return statement is supposed to be #linechart), but will still be useful. – Dude May 24 '19 at 20:46

1 Answers1

0

I had the same problem. I got it working by putting all the code for the svg in a function, then I called it in componentDidMount()

SrednaK
  • 45
  • 6