Mähnenwolf
Mähnenwolf

Reputation: 810

d3.select is not a function, but d3 got imported (* as d3)

I have problems with D3 at the moment.
I tried both of these, only one at a time, but I get the same error.

import * as d3 from "d3";
const d3 = require("d3");

But I get this error message: TypeError: d3.select is not a function

My Code

I am using React / NextJS. I figured maybe it has to be a dynamic import, but nope. What could the problem be?

import Head from "next/head";
import styles from "../styles/Home.module.css";
import { createRef, useEffect, useState } from "react";
import * as d3 from "d3";
// const d3 = require("d3");
// import dynamic from "next/dynamic";

// const d3 = dynamic(() => import("d3"), { ssr: false });


export default function Dthree() {
  let d1 = new Date();
  let d2 = new Date();
  d2.setDate(d2.getDate() + 5);
  let d3 = new Date();
  d3.setDate(d3.getDate() + 10);
  let d4 = new Date();
  d4.setDate(d4.getDate() + 15);

  const [dataset, setDataset] = useState([100, 200, 235, 468, 531]);

  const d3Ref = createRef();

  useEffect(() => {
    let size = 500;
    let svg = d3
      .select(d3Ref.current) // <-- TypeError: d3.select is not a function
      .append("svg")
      .attr("width", size)
      .attr("height", size);

    let rectWidth = 95;
    svg
      .selectAll("rect")
      .data(dataset)
      .enter()
      .append("rect")
      .attr("x", (d, i) => 5 + i * (rectWidth + 5))
      .attr("y", (d) => size - d)
      .attr("width", rectWidth)
      .attr("height", (d) => d)
      .attr("fill", "teal");
  }, [dataset]);

  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>D3</h1>
        <div ref={d3Ref}></div>
      </main>
    </div>
  );
}

Upvotes: 1

Views: 1132

Answers (1)

Michael Rovinsky
Michael Rovinsky

Reputation: 7210

You declare a variable called d3:

let d3 = new Date();

I suppose it's a problem

Also, you don't need 'require' and can use useRef instead of createRef

Upvotes: 2

Related Questions