Home > Back-end >  D3.js keep running into this error TypeError: Cannot read properties of null (reading 'ownerDoc
D3.js keep running into this error TypeError: Cannot read properties of null (reading 'ownerDoc

Time:12-28

When I am trying to create a legend for my d3 graph I keep running into this error

TypeError: Cannot read properties of null (reading 'ownerDocument') at new EnterNode (enter.js:9)

8 export function EnterNode(parent, datum) {

9 this.ownerDocument = parent.ownerDocument;

this only happens once in a while and not always, my d3 configuration;

 private data: SimpleDataModel[] = [
    { name: `Value 1`, value: '25', color: '#254C66' },
    { name: `Value 2`, value: '75', color: '#49A0CC' },
  ];
this.createSvg();
this.createLegend();
private createSvg(): void {
    this.d3
      .select(this.figureElement.nativeElement)
      .append('svg')
      .attr('viewBox', `0 0 ${this.width} ${this.height}`);

    this.svg = this.d3
    .select(this.figureElement.nativeElement)
    .select('svg');

    this.legend = this.svg
      .append('g')
      .attr('id','legend');

    this.graphGroup = this.svg
      .append('g')
      .attr(
        'transform',
        'translate('   this.width / 2   ','   this.height / 2   ')'
      );
  }

  private createLegend(): void {

     const legend1 = this.svg.select('g#legend')
      .data(this.data)   =====>ERROR OCCURS AT THIS LINE
      .enter();

    legend1.append('rect')
      .attr('fill', d => this.colors(d.name))
      .attr('height', 15)
      .attr('width', 15);

    legend1.append('text')
      .attr('x', 18)
      .attr('y', 10)
      .attr('dy', '.15em')
      .text((d, i) => d.name)
      .style('text-anchor', 'start')
      .style('font-size', 24);
    }

Sometimes if I configure my data input differently it works but then other times it does not work. What am I doing wrong?

CodePudding user response:

I figured it out, the error was caused because another g element was being rendered without an id legend on it. Fixed it by using

const legend1 = this.svg.selectAll('g')
      .select('#legend')
      .data(this.data)
      .enter();
  • Related