Introduction to D3.js and Building a Bar Chart in SPFx
What is D3.js?
D3.js, or Data-Driven Documents, is a powerful JavaScript library for producing dynamic, interactive data visualizations in web browsers. It utilizes HTML, SVG (Scalable Vector Graphics), and CSS to bring data to life. D3 is particularly known for its ability to bind arbitrary data to a Document Object Model (DOM), allowing developers to create complex visualizations with minimal effort.
One of the main advantages of D3.js is its flexibility. You can manipulate any aspect of the visualization, making it possible to create everything from simple charts to intricate animations. This flexibility makes D3.js a popular choice among data scientists, analysts, and web developers.
Getting Started with D3.js in SPFx
In this article, we will build a simple bar chart using D3.js in a SharePoint Framework (SPFx) web part. We will use static data for demonstration purposes.
Prerequisites
- Basic knowledge of React and TypeScript.
- A SharePoint Framework development environment set up.
- Node.js and npm installed on your machine.
Step 1: Set Up Your SPFx Project
First, create a new SPFx web part using the Yeoman generator:
yo @microsoft/sharepoint
Choose React as the framework when prompted. Navigate into your project directory after the setup completes:
cd your-project-name
Step 2: Install D3.js
To use D3.js in your project, you need to install it. Run the following command:
npm install d3
npm install --save-dev @types/d3

Step 3: Create the BarChart Component
Now, create a new React component called BarChart.tsx in the src/webparts/yourWebPart/components folder. Below is the complete code for a static bar chart:
import * as React from 'react';
import * as d3 from 'd3';
interface IData {
label: string;
value: number;
}
const data: IData[] = [
{ label: 'A', value: 30 },
{ label: 'B', value: 80 },
{ label: 'C', value: 45 },
{ label: 'D', value: 60 },
{ label: 'E', value: 20 },
{ label: 'F', value: 90 },
{ label: 'G', value: 55 },
];
const BarChart: React.FC = () => {
const svgRef = React.useRef<SVGSVGElement>(null);
React.useEffect(() => {
const svg = d3.select(svgRef.current);
const width = 500;
const height = 300;
const margin = { top: 20, right: 30, bottom: 40, left: 40 };
svg.attr('width', width).attr('height', height);
const x = d3.scaleBand<string>()
.domain(data.map(d => d.label))
.range([margin.left, width - margin.right])
.padding(0.1);
// Use a type assertion here to let TypeScript know that d3.max returns a number | null
const maxValue = d3.max(data, (d: IData) => d.value) as number || 0; // Provide a default value of 0
const y = d3.scaleLinear<number, number>()
.domain([0, maxValue]) // Now using maxValue which is guaranteed to be a number
.nice()
.range([height - margin.bottom, margin.top]);
// Clear previous content
svg.selectAll('*').remove();
svg.append('g')
.attr('transform', `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x));
svg.append('g')
.attr('transform', `translate(${margin.left},0)`)
.call(d3.axisLeft(y));
svg.selectAll('.bar')
.data(data)
.enter()
.append('rect')
.attr('class', 'bar')
.attr('x', (d: IData) => x(d.label)!) // Ensure d.label is treated as string
.attr('y', (d: IData) => y(d.value)) // Ensure d.value is treated as number
.attr('height', (d: IData) => y(0) - y(d.value))
.attr('width', x.bandwidth());
}, []);
return (
<svg ref={svgRef}></svg>
);
};
export default BarChart;
Explanation of the BarChart Code
- Static Data: We define a static array of numbers that will serve as the dataset for our bar chart.
- SVG Reference: We create a reference for the SVG element to manipulate it later with D3.js.
- D3.js Configuration: Inside the
useEffecthook:
- We define the dimensions and margins of the chart.
- We create the x-axis and y-axis scales using D3’s scale functions.
- We append the axes to the SVG element.
- We create rectangles for each data point (bar) and set their positions and dimensions based on the data.
Step 4: Integrate the BarChart Component in Your Web Part
In your main web part component (e.g., MyWebPart.tsx), import and use the BarChart component:
import * as React from 'react';
import { WebPartContext } from '@microsoft/sp-webpart-base';
import BarChart from './BarChart';
interface IMyWebPartProps {
context: WebPartContext;
}
const MyWebPart: React.FC<IMyWebPartProps> = (props) => {
return (
<div>
<h2>Static Bar Chart Example</h2>
<BarChart />
</div>
);
};
export default MyWebPart;
Step 5: Test Your Web Part
- Save all your changes.
- Run the local SharePoint workbench:
gulp serve
- Open the local workbench in your browser. You should see the static bar chart rendered using D3.js.
Conclusion
D3.js is a powerful tool for creating rich, interactive visualizations in web applications. In this article, we demonstrated how to integrate a static bar chart using D3.js into a SharePoint Framework web part. You can extend this example by fetching dynamic data from SharePoint lists or other data sources to create more complex visualizations.
Feel free to experiment with different chart types and datasets to fully explore D3.js’s capabilities!
This draft provides a technical introduction to D3.js and walks through the process of creating a static bar chart in a SharePoint Framework web part. You can adjust any sections or details as needed!
Sure! Here’s a draft for an article that introduces D3.js and provides a practical example using a static bar chart in a SharePoint Framework (SPFx) web part.
Introduction to D3.js and Building a Bar Chart in SPFx
What is D3.js?
D3.js, or Data-Driven Documents, is a powerful JavaScript library for producing dynamic, interactive data visualizations in web browsers. It utilizes HTML, SVG (Scalable Vector Graphics), and CSS to bring data to life. D3 is particularly known for its ability to bind arbitrary data to a Document Object Model (DOM), allowing developers to create complex visualizations with minimal effort.
One of the main advantages of D3.js is its flexibility. You can manipulate any aspect of the visualization, making it possible to create everything from simple charts to intricate animations. This flexibility makes D3.js a popular choice among data scientists, analysts, and web developers.
Getting Started with D3.js in SPFx
In this article, we will build a simple bar chart using D3.js in a SharePoint Framework (SPFx) web part. We will use static data for demonstration purposes.
Prerequisites
- Basic knowledge of React and TypeScript.
- A SharePoint Framework development environment set up.
- Node.js and npm installed on your machine.
Step 1: Set Up Your SPFx Project
First, create a new SPFx web part using the Yeoman generator:
yo @microsoft/sharepoint
Choose React as the framework when prompted. Navigate into your project directory after the setup completes:
cd your-project-name
Step 2: Install D3.js
To use D3.js in your project, you need to install it. Run the following command:
npm install d3
Step 3: Create the BarChart Component
Now, create a new React component called BarChart.tsx in the src/webparts/yourWebPart/components folder. Below is the complete code for a static bar chart:
import * as React from 'react';
import * as d3 from 'd3';
const BarChart: React.FC = () => {
const svgRef = React.useRef<SVGSVGElement | null>(null);
// Static data for the bar chart
const data = [30, 86, 168, 234, 15, 42, 67];
React.useEffect(() => {
if (svgRef.current) {
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove(); // Clear previous content
const width = 500;
const height = 300;
const margin = { top: 20, right: 30, bottom: 30, left: 40 };
const x = d3.scaleBand()
.domain(data.map((_, i) => i.toString()))
.range([margin.left, width - margin.right])
.padding(0.1);
const y = d3.scaleLinear()
.domain([0, d3.max(data)!])
.nice()
.range([height - margin.bottom, margin.top]);
svg.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).tickFormat(i => `Bar ${i}`));
svg.append("g")
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y));
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d, i) => x(i.toString())!)
.attr("y", d => y(d))
.attr("width", x.bandwidth())
.attr("height", d => y(0) - y(d))
.attr("fill", "steelblue");
}
}, [data]);
return <svg ref={svgRef} />;
};
export default BarChart;
Explanation of the BarChart Code
- Static Data: We define a static array of numbers that will serve as the dataset for our bar chart.
- SVG Reference: We create a reference for the SVG element to manipulate it later with D3.js.
- D3.js Configuration: Inside the
useEffecthook:
- We define the dimensions and margins of the chart.
- We create the x-axis and y-axis scales using D3’s scale functions.
- We append the axes to the SVG element.
- We create rectangles for each data point (bar) and set their positions and dimensions based on the data.
Step 4: Integrate the BarChart Component in Your Web Part
In your main web part component (e.g., MyWebPart.tsx), import and use the BarChart component:
import * as React from 'react';
import { WebPartContext } from '@microsoft/sp-webpart-base';
import BarChart from './BarChart';
interface IMyWebPartProps {
context: WebPartContext;
}
const MyWebPart: React.FC<IMyWebPartProps> = (props) => {
return (
<div>
<h2>Static Bar Chart Example</h2>
<BarChart />
</div>
);
};
export default MyWebPart;
Step 5: Test Your Web Part
- Save all your changes.
- Run the local SharePoint workbench:
gulp serve
- Open the local workbench in your browser. You should see the static bar chart rendered using D3.js.
Conclusion
D3.js is a powerful tool for creating rich, interactive visualizations in web applications. In this article, we demonstrated how to integrate a static bar chart using D3.js into a SharePoint Framework web part. You can extend this example by fetching dynamic data from SharePoint lists or other data sources to create more complex visualizations.

Leave a comment