Charts

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.

Recharts data variable
[
    {
        name: xAxisVariable0,
        value: yAxisVariable0
    },
    {
        name: xAxisVariable1,
        value: yAxisVariable1
    },
    // ...
    {
        name: xAxisVariableN,
        value: yAxisVariableN
    },
]

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'

export const dashboardHandler = async (request, response, context) => {
  // finding resource called movies
  const resource = context._admin.findResource('movies')
  // creating new filter, so that we can see only movies released in 2020
  const filter = new Filter({}, resource)
  // finding all records that match provided filter
  const resourceData = await resource.find(filter, { sort: { sortBy: 'year', direction: 'desc' } }, context)
  
  const data = 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.

We will need to parse to Recharts data format.

The next step is creating a chart component we will later on put into our dashboard.

The last part is adding the line chart component to our dashboard.

Last updated