I have created a demo client-side chart web part with the source code on github. This web part allows users to select chart type on the web part properties panel and then renders the chart in the selected chart type using Chart.js library. An interface, IDataSource, was created in the web part and we can implement the interface with all kinds of data sources such as SharePoint, Office Excel, and Rest APIs. For this demo web part, I just implemented the interface with a mock data source class MockDataSource, however we can add any data source class in future as long as the class implements the getData method defined in the IDataSource interface.
Setup development environment and scaffold the project structures
Please follow this guide from Microsoft to setup the SharePoint Framework development environment.
Create data access interface/classes
In this demo, three data access interface/classes need to be created, including ChartJSData DTO class, IDataSoruce interface, and MockDataSoruce class.
Firstly, we need to create a DTO class, ChartJSData, that holds the data read from the data sources and will be rendered using Chart.js charts.
We then create the IDataSource interface with the getData() method signature and implement the interface with a mock data source, MockDataSource.
Import Chart.js library into client-side web part
To import the Chart.js library into the client-side web part, we need add an external entry in the config.json file and point it to the CDN hosted Chart.js file.
Then import the library in the React component file (ChartJs.tsx) that will render the Chart.js charts.
Create and Render the Chart.js charts in client-side web part
In the React component file (ChartJs.tsx), we firstly import the MockDataSource class and ChartJSData class defined earlier.
In the render() method of the ChartJs React component, we add the canvas tag where the Chart.js charts will be drew on.
We then create a private method renderChart() that creates and renders the Chart.js chart object with the data read from the MockDataSource. This method will be called in the both componentDidMount() method and componentDidUpdate() method. The reason to re-render the chart in the componentDidUpdate() method is to allow users changing chart type using the web part properties panel.
We now have the Chart.js library ready to render charts in the demo client-side web part. We can run gulp serve to preview the web part on the local workbench.