πŸ“ŠπŸ“ˆ Create charts using Recharts

necatiozmen

Necati Γ–zmen

Posted on May 28, 2024

πŸ“ŠπŸ“ˆ Create charts using Recharts


refine repo


Introduction

Charts make it easy to represent complex data in a simple and visually appealing way. With charts, you can easily identify trends and patterns and make comparisons across different variables and data types. You can use charts to interpret current data and predict the future.

There are several types of charts you can use to visually represent data. Some of them include Line Charts, Bar Charts, Area Charts, and Scatter charts. The choice of a chart largely depends on the type of data. Different types of charts are suited for different purposes.

There are several libraries for creating charts in the React ecosystem. These React chart libraries include react-flow-charts, react-financial-charts, react-charts and Recharts. In this article, we will explore how to create charts in a Refine project using Recharts.

What is Recharts


Recharts chart

Recharts is a popular, MIT-licensed library for creating charts in React and React-based frameworks like refine. Internally, it uses SVG and some lightweight D3 packages as its dependencies.

Recharts has several built-in components that you can compose to create some of the commonest charts such as Area charts, Bar charts, Pie charts, and Line charts.

As an example, the code below illustrates how you can use Rechart's built-in components to create a Bar chart. The component names are self-explanatory.

import {
  BarChart,
  CartesianGrid,
  XAxis,
  YAxis,
  Tooltip,
  Legend,
  Bar,
} from "recharts";

<BarChart width={730} height={250} data={data}>
  <CartesianGrid strokeDasharray="3 3" />
  <XAxis dataKey="name" />
  <YAxis />
  <Tooltip />
  <Legend />
  <Bar dataKey="pv" fill="#8884d8" />
  <Bar dataKey="uv" fill="#82ca9d" />
</BarChart>;
Enter fullscreen mode Exit fullscreen mode

How to create a Refine project

In this section, we will create a refine demo project.

npm create refine-app@latest
Enter fullscreen mode Exit fullscreen mode

Select the options below when prompted by the command line tool.

βœ” Choose a project template Β· Vite
βœ” What would you like to name your project?: Β· refine-recharts-demo
βœ” Choose your backend service to connect: Β· REST API
βœ” Do you want to use a UI Framework?: Β· Material UI
βœ” Do you want to add example pages?: Β· Yes
βœ” Do you need any Authentication logic?: Β· No
βœ” Choose a package manager: Β· npm
Enter fullscreen mode Exit fullscreen mode

After setting up the project and installing dependencies, use the command below to launch the development server.

npm run dev
Enter fullscreen mode Exit fullscreen mode

Later in this article, we will create charts using Recharts and render them in a dashboard. Let's add a dashboard to the project we have just created.

Create the src/pages/dashboard/list.tsx file. Copy and paste the code below into it. Be aware that the dashboard directory doesn't exist yet. You need to first create it.

```tsx title="src/pages/dashboard/list.tsx"
import React from "react";

export const DashboardPage: React.FC = () => {
return

Hello world!

;
};



The component above renders a simple "Hello world!" text at the moment. We will add more code to it later. Now we need to export the component above. Create the `src/pages/dashboard/index.ts` file. Copy and paste the code below into it.



```ts 
// src/pages/dashboard/index.ts

export { DashboardPage } from "./list";
Enter fullscreen mode Exit fullscreen mode

You can now import the DashboardPage component we created above and render it in the <App /> component. Add the changes below to the src/App.tsx file.

//src/App.tsx
...
//highlight-next-line
import { DashboardPage } from "./pages/dashboard";

function App() {
  return (
    <BrowserRouter>
      <RefineKbarProvider>
        <ColorModeContextProvider>
          <CssBaseline />
          <GlobalStyles styles={{ html: { WebkitFontSmoothing: "auto" } }} />
          <RefineSnackbarProvider>
            <DevtoolsProvider>
              <Refine
              //highlight-start
                dataProvider={{
                  default: dataProvider("https://api.fake-rest.refine.dev"),
                  metrics: dataProvider("https://api.finefoods.refine.dev"),
                }}
                //highlight-end
                notificationProvider={notificationProvider}
                routerProvider={routerBindings}
                resources={[
                  {
                    name: "blog_posts",
                    list: "/blog-posts",
                    create: "/blog-posts/create",
                    edit: "/blog-posts/edit/:id",
                    show: "/blog-posts/show/:id",
                    meta: {
                      canDelete: true,
                    },
                  },
                  {
                    name: "categories",
                    list: "/categories",
                    create: "/categories/create",
                    edit: "/categories/edit/:id",
                    show: "/categories/show/:id",
                    meta: {
                      canDelete: true,
                    },
                  },
                  //highlight-start
                  {
                    name: "dashboard",
                    list: "/dashboard",
                    meta: {
                      label: "Dashboard",
                      dataProviderName: "metrics",
                    },
                  },
                  //highlight-end
                ]}
                options={{
                  syncWithLocation: true,
                  warnWhenUnsavedChanges: true,
                  useNewQueryKeys: true,
                  projectId: "5l4F52-JwXWMu-eZRGwA",
                }}
              >
                <Routes>
                  <Route
                    element={
                      <ThemedLayoutV2 Header={() => <Header sticky />}>
                        <Outlet />
                      </ThemedLayoutV2>
                    }
                  >
                    <Route
                      index
                      element={<NavigateToResource resource="blog_posts" />}
                    />
                    ...
                    //highlight-start
                    <Route path="/dashboard">
                      <Route index element={<DashboardPage />} />
                    </Route>
                    //highlight-end
                    <Route path="*" element={<ErrorComponent />} />
                  </Route>
                </Routes>

                <RefineKbar />
                <UnsavedChangesNotifier />
                <DocumentTitleHandler />
              </Refine>
              <DevtoolsPanel />
            </DevtoolsProvider>
          </RefineSnackbarProvider>
        </ColorModeContextProvider>
      </RefineKbarProvider>
    </BrowserRouter>
  );
}



export default App;
Enter fullscreen mode Exit fullscreen mode

In the code above, we added another data provider. The data provider will fetch data from the fast foods API. It's a dummy API created by the refine team. You can use it to create simple projects when testing out refine. We will use the API to create charts later.

You will now see a dashboard entry in the sidebar. The dashboard will look like the image below. We will create charts and render them in the dashboard in the next sub-sections.

Recharts chart

Before we start creating charts, let's create a simple interface for the data from our API. Create the src/interfaces/index.d.ts file. Copy and paste the interface below into it.

// src/interfaces/index.d.ts

export interface IQueryResult {
  date: string;
  value: number;
}
Enter fullscreen mode Exit fullscreen mode

How to install Recharts

You can install Recharts either from the npm package registry or get its UMD build via a CDN. Depending on your package manager, use one of the commands below to install Recharts.

npm install recharts
Enter fullscreen mode Exit fullscreen mode

Create a Line chart using Recharts

Line charts consist of a series of data points connected using line segments. They are mostly used to represent time series data. You can use Rechart's built-in <LineChart /> component to create a Line chart like so:

<LineChart
  width={730}
  height={250}
  data={data}
  margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
>
  <CartesianGrid strokeDasharray="3 3" />
  <XAxis dataKey="name" />
  <YAxis />
  <Tooltip />
  <Legend />
  <Line type="monotone" dataKey="value" stroke="#8884d8" />
</LineChart>
Enter fullscreen mode Exit fullscreen mode

Charts in general need to have features such as axes, Cartesian grid, legend, and tooltips. Therefore, we need to use the <LineChart /> component with Rechart's built-in general and Cartesian components as in the example above.

The <LineChart /> component has the data prop for passing the data you want to represent on the Line chart. The data should be an array of objects like in the example below.

[
  { name: "a", value: 16 },
  { name: "b", value: 12 },
  { name: "c", value: 18 },
];
Enter fullscreen mode Exit fullscreen mode

Let's create a simple Line chart in our refine project. We will render it in the dashboard we created above. Start by creating the src/pages/dashboard/charts/line-chart.tsx file. Copy and paste the code below into it. The charts directory doesn't exist yet. Start by creating it.

// src/pages/dashboard/charts/line-chart.tsx

import React from "react";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
} from "recharts";

import { IQueryResult } from "../../../interfaces";

export const LineChartComponent: React.FC<{
  dailyOrders: IQueryResult[];
}> = ({ dailyOrders }) => {
  return (
    <ResponsiveContainer width="100%" height="100%" aspect={500 / 300}>
      <LineChart
        width={500}
        height={300}
        data={dailyOrders}
        margin={{
          top: 5,
          right: 30,
          left: 20,
          bottom: 5,
        }}
      >
        <XAxis dataKey="date" />
        <YAxis />
        <Tooltip />
        <Line type="monotone" dataKey="value" stroke="#82ca9d" />
      </LineChart>
    </ResponsiveContainer>
  );
};
Enter fullscreen mode Exit fullscreen mode

In the example above, the <LineChart /> component is wrapped in a responsive container. We will do the same while creating other charts later. We need to export the component we created above so that we can easily import and render it anywhere in our project. Create the src/pages/dashboard/charts/index.ts file. Copy and paste the code below into it.

// src/pages/dashboard/charts/index.ts

export { LineChartComponent } from "./line-chart";
Enter fullscreen mode Exit fullscreen mode

Let's now import the above component and render it in the <DashboardPage /> component. Copy and paste the code below into the src/pages/dashboard/list.tsx file.

// src/pages/dashboard/list.tsx

import React from "react";
import { Grid } from "@mui/material";
import { useApiUrl, useCustom } from "@refinedev/core";

import dayjs from "dayjs";

const query = {
  start: dayjs().subtract(7, "days").startOf("day"),
  end: dayjs().startOf("day"),
};

import { LineChartComponent } from "./charts";

import { IQueryResult } from "../../interfaces";

export const formatDate = new Intl.DateTimeFormat("en-US", {
  month: "short",
  year: "numeric",
  day: "numeric",
});

const transformData = (data: IQueryResult[]): IQueryResult[] => {
  return data.map(({ date, value }) => ({
    date: formatDate.format(new Date(date)),
    value,
  }));
};

export const DashboardPage: React.FC = () => {
  const API_URL = useApiUrl("metrics");

  const { data: dailyRevenue } = useCustom({
    url: `${API_URL}/dailyRevenue`,
    method: "get",
    config: {
      query,
    },
    queryOptions: {
      select: ({ data }) => {
        return { data: transformData(data.data) };
      },
    },
  });

  const { data: dailyOrders } = useCustom({
    url: `${API_URL}/dailyOrders`,
    method: "get",
    config: {
      query,
    },
    queryOptions: {
      select: ({ data }) => {
        return { data: transformData(data.data) };
      },
    },
  });

  const { data: newCustomers } = useCustom({
    url: `${API_URL}/newCustomers`,
    method: "get",
    config: {
      query,
    },
    queryOptions: {
      select: ({ data }) => {
        return { data: transformData(data.data) };
      },
    },
  });

  return (
    <Grid
      container
      justifyContent="baseline"
      alignItems={"stretch"}
      spacing={2}
    >
      <Grid item xs={12} sm={6}>
        <LineChartComponent dailyOrders={dailyOrders?.data ?? []} />
      </Grid>
    </Grid>
  );
};
Enter fullscreen mode Exit fullscreen mode

In the code above, we are using the useCustom hook to make custom query requests to the backend. The useCustom hook uses TanStack Query's useQuery hook under the hook. We have been querying the daily revenue, daily orders, and new customers of a restaurant business for the last seven days. We will represent the data in different types of charts. The dashboard should now have a Line chart that looks like the image below.


Recharts chart

There are several Line chart variants you can create using Rechart's built-in components. For more complex charts, check out the Recharts documentation.

Create Area chart using Recharts

Recharts has the built-in <AreaChart /> component for creating area charts. You can compose the built-in <AreaChart /> component to create complex area charts in your React project.

You can use the <AreaChart /> component's data prop to pass the data you want to represent on an area chart. Like in the previous example, your data should be an array of objects.

[
  { name: "Name A", data: 4000 },
  { name: "Name B", data: 3000 },
];
Enter fullscreen mode Exit fullscreen mode

To represent the above data in an area chart, you can use the <AreaChart /> component as in the example below. As before, the component names are self-explanatory.

<AreaChart
  width={500}
  height={300}
  data={data}
  margin={{
    top: 10,
    right: 30,
    left: 0,
    bottom: 0,
  }}
>
  <XAxis dataKey="name" />
  <YAxis />
  <Tooltip />
  <Area type="monotone" dataKey="data" stroke="#8884d8" fill="#8884d8" />
</AreaChart>
Enter fullscreen mode Exit fullscreen mode

Let's now add an area chart to the refine project we created above. Create the src/pages/dashboard/charts/area-chart.tsx file. Copy and paste the code below into it.

// dashboard/charts/area-chart.tsx

import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
} from "recharts";

import { IQueryResult } from "../../../interfaces";

export const AreaChartComponent: React.FC<{ dailyRevenue: IQueryResult[] }> = ({
  dailyRevenue,
}) => {
  return (
    <ResponsiveContainer width="100%" height="100%" aspect={500 / 300}>
      <AreaChart
        width={500}
        height={300}
        data={dailyRevenue}
        margin={{
          top: 10,
          right: 30,
          left: 0,
          bottom: 0,
        }}
      >
        <XAxis dataKey="date" />
        <YAxis />
        <Tooltip />
        <Area type="monotone" dataKey="value" stroke="#8884d8" fill="#8884d8" />
      </AreaChart>
    </ResponsiveContainer>
  );
};
Enter fullscreen mode Exit fullscreen mode

In the example above, we are representing the daily revenue of a restaurant business in an area chart. We are fetching the data in our dashboard component and passing it as a prop to the above component. Once again we are wrapping the area chart in a responsive container.

You need to export the above component by adding the changes below to the src/pages/dashboard/charts/index.ts file.

// pages/dashboard/charts/index.ts

export { LineChartComponent } from "./line-chart";
//highlight-next-line
export { AreaChartComponent } from "./area-chart";
Enter fullscreen mode Exit fullscreen mode

We can now import and render the above component in the <DashboardPage /> component. Add the changes below to the src/pages/dashboard/list.tsx file.

...

import {
  LineChartComponent,
  //highlight-next-line
  AreaChartComponent,
} from "./charts";

 ...

export const DashboardPage: React.FC = () => {

 ...

  return (
    <Grid
      container
      justifyContent="baseline"
      alignItems={"stretch"}
      spacing={2}
    >
      <Grid item xs={12} sm={6}>
        <LineChartComponent dailyOrders={dailyOrders?.data ?? []} />
      </Grid>
      //highlight-start
      <Grid item xs={12} sm={6}>
        <AreaChartComponent dailyRevenue={dailyRevenue?.data ?? []} />
      </Grid>
      //highlight-end
    </Grid>
  );
};
Enter fullscreen mode Exit fullscreen mode

Your dashboard should now have a simple area chart that looks like the image below.


Recharts chart

There are several types of Area charts. What we have created above is a simple Area chart. Recharts has built-in functionality for implementing most of them. For more, check out the documentation.

Create a Bar chart using Recharts

Bar charts are among the most common charts for visualizing data. You can use it to visually represent categorical data. Recharts has the built-in <BarChart /> component for creating bar charts.

Like the other types of charts, the data you want to represent on a bar chart should be an array of objects. You need to pass it to the <BarChart /> component as the value of the data prop.

Let's add a bar chart to the dashboard in the refine project we created above. Create the src/pages/dashboard/charts/bar-chart.tsx file. Copy and paste the code below into it.

// pages/dashboard/charts/bar-chart.tsx

import React from "react";

import {
  BarChart,
  Bar,
  Rectangle,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
} from "recharts";

import { IQueryResult } from "../../../interfaces";

export const BarChartComponent: React.FC<{ newCustomers: IQueryResult[] }> = ({
  newCustomers,
}) => {
  return (
    <ResponsiveContainer width="100%" height="100%" aspect={500 / 300}>
      <BarChart
        width={500}
        height={300}
        data={newCustomers}
        margin={{
          top: 5,
          right: 30,
          left: 20,
          bottom: 5,
        }}
      >
        <XAxis dataKey="date" />
        <YAxis />
        <Tooltip />
        <Bar
          dataKey="value"
          fill="#8884d8"
          activeBar={<Rectangle fill="pink" stroke="blue" />}
        />
      </BarChart>
    </ResponsiveContainer>
  );
};
Enter fullscreen mode Exit fullscreen mode

We need to export the component above. Add the changes below to the src/pages/dashboard/charts/index.ts file.

export { LineChartComponent } from "./line-chart";
export { AreaChartComponent } from "./area-chart";
//highlight-next-line
export { BarChartComponent } from "./bar-chart";
Enter fullscreen mode Exit fullscreen mode

We can now import and render the above component. Add the changes below to the src/pages/dashboard/list.tsx file.

...

import {
  LineChartComponent,
  AreaChartComponent,
  //highlight-next-line
  BarChartComponent,
} from "./charts";

...

export const DashboardPage: React.FC = () => {
 ...

  return (
    <Grid
      container
      justifyContent="baseline"
      alignItems={"stretch"}
      spacing={2}
    >
      <Grid item xs={12} sm={6}>
        <LineChartComponent dailyOrders={dailyOrders?.data ?? []} />
      </Grid>
      <Grid item xs={12} sm={6}>
        <AreaChartComponent dailyRevenue={dailyRevenue?.data ?? []} />
      </Grid>
      //highlight-start
      <Grid item xs={12} sm={6}>
        <BarChartComponent newCustomers={newCustomers?.data ?? []} />
      </Grid>
     //highlight-end
    </Grid>
  );
};
Enter fullscreen mode Exit fullscreen mode

After rendering the above component, your dashboard should now have a bar chart that looks like the image below.


Recharts chart

Create Scatter chart using Recharts

Scatter charts are useful to graphically represent the relationship between two variables. Like the other charts mentioned above, Recharts has the built-in <ScatterChart /> component for creating scatter charts.

Let's create a simple scatter chart in this article. Create the src/pages/dashboard/charts/scatter-chart.tsx file. Copy and paste the code below into it.

import React from "react";
import {
  ScatterChart,
  Scatter,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
} from "recharts";

import { IQueryResult } from "../../../interfaces";

const formatData = (
  dailyOrders: IQueryResult[],
  newCustomers: IQueryResult[],
) => {
  const formattedData = [];

  for (let i = 0; i < dailyOrders.length; i++) {
    if (!dailyOrders[i] || !newCustomers[i]) continue;

    if (dailyOrders[i].date === newCustomers[i].date) {
      formattedData.push({
        date: dailyOrders[i].date,
        dailyOrders: dailyOrders[i].value,
        newCustomers: newCustomers[i].value,
      });
    }
  }

  return formattedData;
};

export const ScatterChartComponent: React.FC<{
  dailyOrders: IQueryResult[];
  newCustomers: IQueryResult[];
}> = ({ dailyOrders, newCustomers }) => {
  const formattedData = formatData(dailyOrders, newCustomers);

  return (
    <ResponsiveContainer width="100%" height="100%" aspect={500 / 300}>
      <ScatterChart
        width={500}
        height={300}
        margin={{
          top: 20,
          right: 20,
          bottom: 20,
          left: 20,
        }}
      >
        <XAxis type="number" dataKey="dailyOrders" name="Orders" />
        <YAxis type="number" dataKey="newCustomers" name="Customers" />
        <Tooltip cursor={{ strokeDasharray: "3 3" }} />
        <Scatter name="A school" data={formattedData} fill="#8884d8" />
      </ScatterChart>
    </ResponsiveContainer>
  );
};
Enter fullscreen mode Exit fullscreen mode

In the example above, we wrapped the chart in a responsive container and passed the data to the Scatter component instead of the ScatterChart. Similar to the other charts we have already looked at, the data should be an array of objects.

In the example above, we had to transform the data because we wanted to determine the relationship between two variables(daily orders and new customers).

Let's export the above component. Add the changes below to the src/pages/dashboard/charts/index.ts file.

export { LineChartComponent } from "./line-chart";
export { AreaChartComponent } from "./area-chart";
export { BarChartComponent } from "./bar-chart";
//highlight-next-line
export { ScatterChartComponent } from "./scatter-chart";
Enter fullscreen mode Exit fullscreen mode

You can now import and render the above component in the dashboard. Add the changes below to the src/pages/dashboard/list.tsx file.

// src/pages/dashboard/list.tsx

...

import {
  LineChartComponent,
  AreaChartComponent,
  BarChartComponent,
  //highlight-next-line
  ScatterChartComponent,
} from "./charts";

i...

export const DashboardPage: React.FC = () => {
 ...

  return (
    <Grid
      container
      justifyContent="baseline"
      alignItems={"stretch"}
      spacing={2}
    >
      <Grid item xs={12} sm={6}>
        <LineChartComponent dailyOrders={dailyOrders?.data ?? []} />
      </Grid>
      <Grid item xs={12} sm={6}>
        <AreaChartComponent dailyRevenue={dailyRevenue?.data ?? []} />
      </Grid>
      <Grid item xs={12} sm={6}>
        <BarChartComponent newCustomers={newCustomers?.data ?? []} />
      </Grid>
      //highlight-start
      <Grid item xs={12} sm={6}>
        <ScatterChartComponent
          dailyOrders={dailyOrders?.data ?? []}
          newCustomers={newCustomers?.data ?? []}
        />
      </Grid>
      //highlight-end
    </Grid>
  );
};
Enter fullscreen mode Exit fullscreen mode

After rendering the above component, the dashboard should now have a scatter chart that looks like the image below.


Recharts chart

Create a Pie chart using Recharts

A pie chart is one of the most common and easy-to-understand charts. It is a circular graph that is split into multiple sectors. Each sector in a pie chart represents a particular category of data and its size is proportional to the quantity of the category it represents.

In this section, we will create a simple Pie chart using Recharts. Let's start by creating the src/pages/dashboard/charts/pie-chart.tsx file. Copy and paste the code below into it.

import React from "react";
import { PieChart, Pie, ResponsiveContainer } from "recharts";

import { IQueryResult } from "../../../interfaces";

export const PieChartComponent: React.FC<{ dailyOrders: IQueryResult[] }> = ({
  dailyOrders,
}) => {
  return (
    <ResponsiveContainer width="100%" height="100%" aspect={300 / 300}>
      <PieChart width={300} height={300}>
        <Pie
          data={dailyOrders}
          dataKey="value"
          nameKey="date"
          cx="50%"
          cy="40%"
          outerRadius={150}
          fill="#82ca9d"
          label
        />
      </PieChart>
    </ResponsiveContainer>
  );
};
Enter fullscreen mode Exit fullscreen mode

Let's export the above component so that we can import it anywhere in our application. Add the changes below to the src/pages/dashboard/charts/index.ts file.

export { LineChartComponent } from "./line-chart";
export { AreaChartComponent } from "./area-chart";
export { BarChartComponent } from "./bar-chart";
export { ScatterChartComponent } from "./scatter-chart";
//highligh-next-line
export { PieChartComponent } from "./pie-chart";
Enter fullscreen mode Exit fullscreen mode

Let's import and render the above component in our dashboard. Add the changes below to the src/pages/dashboard/list.tsx file.

...

import {
  LineChartComponent,
  AreaChartComponent,
  BarChartComponent,
  ScatterChartComponent,
  //highlight-next-line
  PieChartComponent,
} from "./charts";

...

  return (
    <Grid
      container
      justifyContent="baseline"
      alignItems={"stretch"}
      spacing={2}
    >
      <Grid item xs={12} sm={6}>
        <LineChartComponent dailyOrders={dailyOrders?.data ?? []} />
      </Grid>
      <Grid item xs={12} sm={6}>
        <AreaChartComponent dailyRevenue={dailyRevenue?.data ?? []} />
      </Grid>
      <Grid item xs={12} sm={6}>
        <BarChartComponent newCustomers={newCustomers?.data ?? []} />
      </Grid>
      <Grid item xs={12} sm={6}>
        <ScatterChartComponent
          dailyOrders={dailyOrders?.data ?? []}
          newCustomers={newCustomers?.data ?? []}
        />
      </Grid>
      //highlight-start
      <Grid item xs={12} sm={6}>
        <PieChartComponent dailyOrders={dailyOrders?.data ?? []} />
      </Grid>
      //highlight-end
    </Grid>
  );
};
Enter fullscreen mode Exit fullscreen mode

Your dashboard should now have a Pie chart that looks like the image below.


Recharts chart

Create TreeMap using Recharts

A Treemap is a data visualization tool similar to a Pie chart. However, instead of using a circular graph and sectors to represent data, a Treemap instead uses rectangles and nested rectangles.

With a Treemap, a rectangle represents a category, and nested rectangles represent sub-categories within a category. Recharts has the built-in <Treemap /> component for creating Treemaps. You can pass the data as the value of the data attribute.

Let's add a simple Treemap to our dashboard. Create the src/pages/dashboard/charts/treemap.tsx file. Copy and paste the code below into it.

import React from "react";
import { Treemap, ResponsiveContainer } from "recharts";

const data = [
  {
    name: "axis",
    children: [
      { name: "Axes", size: 1302 },
      { name: "Axis", size: 24593 },
      { name: "AxisGridLine", size: 652 },
      { name: "AxisLabel", size: 636 },
      { name: "CartesianAxes", size: 6703 },
    ],
  },
  {
    name: "controls",
    children: [
      { name: "AnchorControl", size: 2138 },
      { name: "ClickControl", size: 3824 },
      { name: "Control", size: 1353 },
      { name: "ControlList", size: 4665 },
      { name: "DragControl", size: 2649 },
      { name: "ExpandControl", size: 2832 },
      { name: "HoverControl", size: 4896 },
      { name: "IControl", size: 763 },
      { name: "PanZoomControl", size: 5222 },
      { name: "SelectionControl", size: 7862 },
      { name: "TooltipControl", size: 8435 },
    ],
  },
  {
    name: "data",
    children: [
      { name: "Data", size: 20544 },
      { name: "DataList", size: 19788 },
      { name: "DataSprite", size: 10349 },
      { name: "EdgeSprite", size: 3301 },
      { name: "NodeSprite", size: 19382 },
      {
        name: "render",
        children: [
          { name: "ArrowType", size: 698 },
          { name: "EdgeRenderer", size: 5569 },
          { name: "IRenderer", size: 353 },
          { name: "ShapeRenderer", size: 2247 },
        ],
      },
      { name: "ScaleBinding", size: 11275 },
      { name: "Tree", size: 7147 },
      { name: "TreeBuilder", size: 9930 },
    ],
  },
  {
    name: "events",
    children: [
      { name: "DataEvent", size: 7313 },
      { name: "SelectionEvent", size: 6880 },
      { name: "TooltipEvent", size: 3701 },
      { name: "VisualizationEvent", size: 2117 },
    ],
  },
  {
    name: "legend",
    children: [
      { name: "Legend", size: 20859 },
      { name: "LegendItem", size: 4614 },
      { name: "LegendRange", size: 10530 },
    ],
  },
];

export const TreemapComponent: React.FC = () => {
  return (
    <ResponsiveContainer width="100%" height="100%" aspect={500 / 300}>
      <Treemap
        width={500}
        height={300}
        data={data}
        dataKey="size"
        aspectRatio={500 / 300}
        stroke="#fff"
        fill="#8884d8"
      />
    </ResponsiveContainer>
  );
};
Enter fullscreen mode Exit fullscreen mode

In the example above, we have hard-coded the data because the API doesn't have a dataset we can use to create a Treemap. In a typical real-world project, you will retrieve the data from an API. You can export the above component from the src/pages/dashboard/charts/index.ts file like so:

export { LineChartComponent } from "./line-chart";
export { AreaChartComponent } from "./area-chart";
export { BarChartComponent } from "./bar-chart";
export { ScatterChartComponent } from "./scatter-chart";
export { PieChartComponent } from "./pie-chart";
//highlight-next-line
export { TreemapComponent } from "./treemap";
Enter fullscreen mode Exit fullscreen mode

You can now import the above component and render it in the dashboard.

import React from "react";
import { Grid } from "@mui/material";
import { useApiUrl, useCustom } from "@refinedev/core";

import dayjs from "dayjs";

const query = {
  start: dayjs().subtract(7, "days").startOf("day"),
  end: dayjs().startOf("day"),
};

import {
  LineChartComponent,
  AreaChartComponent,
  BarChartComponent,
  ScatterChartComponent,
  PieChartComponent,
  //highlight-next-line
  TreemapComponent,
} from "./charts";

import { IQueryResult } from "../../interfaces";

export const formatDate = new Intl.DateTimeFormat("en-US", {
  month: "short",
  year: "numeric",
  day: "numeric",
});

const transformData = (data: IQueryResult[]): IQueryResult[] => {
  return data.map(({ date, value }) => ({
    date: formatDate.format(new Date(date)),
    value,
  }));
};

export const DashboardPage: React.FC = () => {
  const API_URL = useApiUrl("metrics");

  const { data: dailyRevenue } = useCustom({
    url: `${API_URL}/dailyRevenue`,
    method: "get",
    config: {
      query,
    },
    queryOptions: {
      select: ({ data }) => {
        return { data: transformData(data.data) };
      },
    },
  });

  const { data: dailyOrders } = useCustom({
    url: `${API_URL}/dailyOrders`,
    method: "get",
    config: {
      query,
    },
    queryOptions: {
      select: ({ data }) => {
        return { data: transformData(data.data) };
      },
    },
  });

  const { data: newCustomers } = useCustom({
    url: `${API_URL}/newCustomers`,
    method: "get",
    config: {
      query,
    },
    queryOptions: {
      select: ({ data }) => {
        return { data: transformData(data.data) };
      },
    },
  });

  return (
    <Grid
      container
      justifyContent="baseline"
      alignItems={"stretch"}
      spacing={2}
    >
      <Grid item xs={12} sm={6}>
        <LineChartComponent dailyOrders={dailyOrders?.data ?? []} />
      </Grid>
      <Grid item xs={12} sm={6}>
        <AreaChartComponent dailyRevenue={dailyRevenue?.data ?? []} />
      </Grid>
      <Grid item xs={12} sm={6}>
        <BarChartComponent newCustomers={newCustomers?.data ?? []} />
      </Grid>
      <Grid item xs={12} sm={6}>
        <ScatterChartComponent
          dailyOrders={dailyOrders?.data ?? []}
          newCustomers={newCustomers?.data ?? []}
        />
      </Grid>
      <Grid item xs={12} sm={6}>
        <PieChartComponent dailyOrders={dailyOrders?.data ?? []} />
      </Grid>
      //highlight-start
      <Grid item xs={12} sm={6}>
        <TreemapComponent />
      </Grid>
      //highlight-end
    </Grid>
  );
};
Enter fullscreen mode Exit fullscreen mode

Your dashboard should now have a Treemap that looks like the image below.


Recharts chart

Conclusion

Sometimes you may have to integrate data visualization in your React project. Charts make it easy to present data in an easy-to-understand and visually appealing way.

There are several frameworks for creating charts in React. Recharts is one of the most popular and feature-rich packages for creating charts in a React project or React-based frameworks such as refine.

Recharts support several types of charts out of the box. In this article, we have only explored a subset of charts you can create using Recharts. Check the documentation for details.

πŸ’– πŸ’ͺ πŸ™… 🚩
necatiozmen
Necati Γ–zmen

Posted on May 28, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related