- Published on
SharePoint list data displayed using PnP Chart in the SharePoint Framework (SPFx) webpart
This article explains how to display SharePoint list data using PnP Chart in the SharePoint Framework (SPFx).
PnP Chart makes it simple to visualize list data using Chart.js charts within your web part.
📦 Install dependencies
Install the PnP React controls and PnP JS libraries:
npm install @pnp/spfx-controls-react --save --save-exact
npm install @pnp/sp --save --save-exact
💻 Implementation
Add the following code inside your React component to render the chart:
@autobind
private async _loadAsyncData(): Promise<void> {
const salesList: any[] = await sp.web.lists.getByTitle("Sales").items.select("Title","Sales").get();
let labels: string[] = [];
let dataValues: number[] = [];
salesList.forEach(item => {
labels.push(item.Title);
dataValues.push(item.Sales);
});
const chartData = {
labels: labels,
datasets: [{
label: "My Sales",
data: dataValues,
backgroundColor: [
"#f44336", "#2196f3", "#ff9800", "#4caf50", "#9c27b0"
]
}]
};
this.setState({ chartData });
}
Render the chart using PnP Chart:
public render(): React.ReactElement<ISpfxPnpChartProps> {
return (
<div className={styles.spfxPnpChart}>
<ChartControl
type={ChartType.Bar}
data={this.state.chartData}
options={{ responsive: true, title: { display: true, text: "Sales Data" } }}
/>
</div>
);
}
🚀 Deploy the solution
Build and package your SPFx solution:
gulp build
gulp bundle --ship
gulp package-solution --ship
Upload the .sppkg
file to your App Catalog, deploy it, and add the web part to your SharePoint site.
🧭 Summary
You’ve successfully implemented the PnP Chart control in SPFx to visualize SharePoint list data dynamically using Chart.js.
📂 GitHub Source
View full SPFx project on GitHub:SharePoint list data displayed using PnP Chart in the SharePoint Framework (SPFx) webpart
Author
- Ravichandran@Hi_Ravichandran