How to Use D3.js in Next.js

2/13/2024

Tutorials
placeholder

Adding D3.js to your Next.js Application

D3 is a JavaScript data visualization library. Here are the steps to implement D3 in Next.js 14.1.

Install D3 and the corresponding typescript declarations.

npm install d3 @types/d3

Create a new file in your /components directory, and if you don't have a /components directory, create one in the root of your project. We can call the file D3Component.tsx.

For the sake of simplicity, we will implement the most basic barplot in D3.js from:

https://d3-graph-gallery.com/graph/barplot_basic.html

Here’s an example of a D3 component in action:

Create the file with the following contents:

"use client"
import React, { useEffect } from 'react';
import * as d3 from 'd3';
import { DSVRowString } from 'd3';

interface Data {
    Country: string;
    Value: number;
}

const D3Component = () => {
    useEffect(() => {
        d3.select("#chart").select("svg").remove();
        // set the dimensions and margins of the graph
        var margin = { top: 30, right: 30, bottom: 70, left: 60},
            width = 460 - margin.left - margin.right,
            height = 400 - margin.top - margin.bottom;

        // append the svg object to the body of the page
        var svg = d3.select("#chart")
            .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 + ")");

        // Parse the Data
        d3.csv<Data>("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/7_OneCatOneNum_header.csv", 
            function(data: DSVRowString<string>): Data | null {
                if (!data) return null;

                return {
                    Country: data.Country,
                    Value: +data.Value
                };
            }).then(function(data: Data[]) {
                // X axis
                var x = d3.scaleBand()
                    .range([ 0, width ])
                    .domain(data.map(function(d:Data) { return d.Country; }))
                    .padding(0.2);
                svg.append("g")
                    .attr("transform", "translate(0," + height + ")")
                    .call(d3.axisBottom(x))
                    .selectAll("text")
                    .attr("transform", "translate(-10,0)rotate(-45)")
                    .style("text-anchor", "end");

                // Add Y axis
                var y = d3.scaleLinear()
                    .domain([0, 13000])
                    .range([ height, 0]);
                svg.append("g")
                    .call(d3.axisLeft(y));

                // Bars
                svg.selectAll("mybar")
                .data(data)
                .enter()
                .append("rect")
                .attr("x", function(d) { return x(d.Country) ?? 0; })
                .attr("y", function(d) { return y(d.Value) ?? 0; })
                .attr("width", x.bandwidth())
                .attr("height", function(d) { return height - (y(d.Value) ?? 0); })
                .attr("fill", "#69b3a2")
            });
    }, []);

    return <div id="chart"></div>;
};

export default D3Component;

This will create a simple bar chart component using D3 in your Next.js app.

You can use the D3 component within your Next.js application as you normally would any React component:

import D3Component from '../components/D3Component';

export default function Home() {
    return (
        <div>
            <D3Component />
        </div>
    );
}

Subscribe for Email Updates

And get a free whitepaper! Dont miss a single update from Floorism! Subscribe to the email list now!

Copyright © 2024 Floorism, Inc