Denis
Denis

Reputation: 65

D3 getting errors

I understand that this type of question was asked many times. Still, honestly, I don't know why I got attr.js:30 Error: <path> attribute d: Expected number, "M0,NaNL400,NaN" i was following the exact tutorial of https://www.youtube.com/watch?v=SnkpNCxHSkc even I following same steps.

    import React, { useState, useRef, useEffect } from "react";
import * as d3 from 'd3'

export const Chart = React.forwardRef((props, ref) => {
    const data = useState([35, 78, 38]);
    const svgRef = useRef();


    useEffect(() => {
        //setting up svg
        const w = 400;
        const h = 100;
        const svg = d3.select(svgRef.current)
            .attr('width', w)
            .attr('height', h)
            .style('background', '#d3d3d4')
            .style('margin-left', '10')
            .style('margin-top', '10')
            .style('overflow', 'visible')

        //setting up scaling
        const xScale = d3.scaleLinear()
            .domain([0, data.length - 1])
            .range([0, w]);

        const yScale = d3.scaleLinear()
            .domain([0, h])
            .range([h, 0]);
            
        const generateScaledLine = d3.line()
            .x((d, i) => xScale(i))
            .y(yScale) 
            .curve(d3.curveCardinal)
           

        //setting up axis
        /*const xAxis = d3.axisBottom(xScale)
            .ticks(data.length)
            .tickFormat(i=>i+1);
        const yAxis = d3.axisLeft(yScale)
            .ticks(5);
        svg.append('g')
           .call(xAxis)
           .attr('transform', `translate(0 , ${h})`);
        svg.append('g')
            .call(yAxis)*/

        //setting up the data for the svg 
        svg.selectAll('.line')
            .data([data])
            .join('path')
            .attr('d', d => generateScaledLine(d))
            .attr('fill', 'none')
            .attr('stroke', 'black');


    }, [data]);
    return ( 
    <div>
        <svg ref={ svgRef } />  
    </div>

    );
});

Note: I am pretty new in this library. Can someone give me some excellent examples for react 18? Thanks in advance .

Upvotes: 1

Views: 195

Answers (1)

Simon D
Simon D

Reputation: 6269

The issue here is that you are passing in your data array wrapped in square brackets. I checked the video you referenced and this is also how the tutor does it too but I'm not sure why it worked in his example but it shouldn't...

   svg.selectAll('.line')
      .data([data]) // <----------- Issue here

Since your data variable is already an array, you can use it like this:

   svg.selectAll('.line')
      .data(data) // <----------- Remove square brackets

I tested this myself and I get a graph like this:

enter image description here

Upvotes: 1

Related Questions