A simple way to implement charts with your AdminJS instance is to use Recharts library and Admin's API.
In order to provide custom components on your dashboard you will have to override the dashboard entirely. The dashboard customization article will come in handy.
In your dashboard handler, you will need to fetch and format the required data for charts. For purposes of this guide, we will be using Recharts, which requires data to be passed in an array of objects.
Let's assume our database contains a table called movies, which contains three columns - 'title', 'year', and 'score'.
dashboard.handler.ts
import { Filter } from'adminjs'exportconstdashboardHandler=async (request, response, context) => {// finding resource called moviesconstresource=context._admin.findResource('movies')// creating new filter, so that we can see only movies released in 2020constfilter=newFilter({}, resource)// finding all records that match provided filterconstresourceData=awaitresource.find(filter, { sort: { sortBy:'year', direction:'desc' } }, context)constdata=resourceData.map((item) =>item.toJSON(context.currentAdmin))return data}
However, currently, the data variable is an array that contains all the records in the following manner.
data variable
[{ params: { id:2104, title:'Arrival', year:2018, score:84 }, baseError:null,// ...},{ params: { id:2226, title:'Harry Potter and the Goblet of Fire', year:2018, score:96 }, baseError:null,// ...},// ...]
We will need to parse to Recharts data format.
dashboard.handler.ts
// ...constyears=Array.from(newSet(data?.map((item) =>item.params.year))) // Set leaves only unique values, but we need an Arrayconstchartdata=years.map(year => { // for every year that we've gotconstscoreArr=data?.filter(filterItem =>filterItem.params.year === year) // find movies from a certain year.map(mapItem =>mapItem.params.score) // create an array of all the scores from that yearreturn ( { name: year, score: scoreArr.reduce((a, b) => a + b,0) / scoreArr.length // create average valuefrom the score array }) })return chartdata
The next step is creating a chart component we will later on put into our dashboard.