DEV Community

Cover image for Visualizing Sales Data with CanvasJS and React-Table
Manoj Mohan
Manoj Mohan

Posted on

1

Visualizing Sales Data with CanvasJS and React-Table

In today's data-driven world, combining tabular data presentations with visualizations is crucial for effective analysis. This guide demonstrates how to use Tanstack React-Table for data management and CanvasJS for visualization, creating a cohesive dashboard that tells a complete data story.

Why This Combination?

  • React Table: Robust table management with sorting/filtering capabilities
  • CanvasJS: Rich interactive charting library

Prerequisites

To follow along, ensure you have the following dependencies installed in your React project:

  • @tanstack/react-table
  • @canvasjs/react-charts

Step-by-Step Explanation

  1. Import required packages
import React from 'react';
import {
  createColumnHelper,
  useReactTable,
  getCoreRowModel,
  flexRender,
} from '@tanstack/react-table';
import CanvasJSReact from '@canvasjs/react-charts';

const CanvasJSChart = CanvasJSReact.CanvasJSChart;
Enter fullscreen mode Exit fullscreen mode

2. Sample Data
The sample data is structured as an array of objects. Each object represents a product with its name and quarterly sales figures. For example:

const data = [
  {
    product: 'Product A',
    'Quarter 1': 500,
    'Quarter 2': 600,
    'Quarter 3': 700,
    'Quarter 4': 750,
  },
  // ... other products
];
Enter fullscreen mode Exit fullscreen mode

3. Defining Table Columns:
In any table-based application, defining the structure of the table is a foundational step. In our example, we use the @tanstack/react-table library to manage our sales data, and the column definitions determine how that data is organized and displayed.

const columnHelper = createColumnHelper();
const columns = [
  columnHelper.accessor('product', {
    header: 'Product',
  }),
  columnHelper.accessor('Quarter 1', {
    header: 'Sales Q1 (Units)',
  }),
  columnHelper.accessor('Quarter 2', {
    header: 'Sales Q2 (Units)',
  }),
  columnHelper.accessor('Quarter 3', {
    header: 'Sales Q3 (Units)',
  }),
  columnHelper.accessor('Quarter 4', {
    header: 'Sales Q4 (Units)',
  }),
];
Enter fullscreen mode Exit fullscreen mode

4. Initializing the Table
Once we've defined our data and column structure, the next step is to bring the table to life. This is where @tanstack/react-table shines, providing a powerful yet flexible way to manage table state and behavior. In our example, we initialize the table inside the App component using the useReactTable hook.

const table = useReactTable({
  data,
  columns,
  getCoreRowModel: getCoreRowModel(),
});
Enter fullscreen mode Exit fullscreen mode

5. Generating Data for Chart
To bring our sales data to life in a visual format, we need to transform the table data into a structure that CanvasJS can understand. The generateChartData function handles this crucial step, converting the table's row data into multi-series chart data:

const generateChartData = () => {
  return table.getRowModel().rows.map((row) => {
    const product = row.getValue("product");
    return {
      type: 'column',
      name: product,
      showInLegend: true,
      dataPoints: [
        { label: 'Quarter 1', y: row.getValue('Quarter 1') },
        { label: 'Quarter 2', y: row.getValue('Quarter 2') },
        { label: 'Quarter 3', y: row.getValue('Quarter 3') },
        { label: 'Quarter 4', y: row.getValue('Quarter 4') },
      ],
    };
  });
};
Enter fullscreen mode Exit fullscreen mode

6. Configuring the Chart
To display our sales data effectively, we need to configure the CanvasJS chart with options that define its appearance and behavior. The options object sets up the chart's title, axes, and data, bringing the multi-series visualization to life.

const options = {
  title: {
    text: 'Comparing Sales',
  },
  theme: "light2",
  axisY: {
    title: 'Quantity',
  },
  toolTip: {
    shared: true
  },
  axisY2: {
    title: 'Price',
    valueFormatString: '#0.00',
  },
  data: generateChartData(),
};
Enter fullscreen mode Exit fullscreen mode

7. Rendering the Table
With our table initialized, it’s time to display the sales data visually. The rendering step uses the table instance from @tanstack/react-table to create an HTML table, showing product names and quarterly sales in a structured format.

<table style={{ borderCollapse: 'collapse', marginBottom: '20px' }}>
  <thead>
    {table.getHeaderGroups().map((headerGroup) => (
      <tr key={headerGroup.id}>
        {headerGroup.headers.map((header) => (
          <th
            key={header.id}
            style={{ border: '1px solid black', padding: '8px' }}
          >
            {header.isPlaceholder
              ? null
              : flexRender(
                  header.column.columnDef.header,
                  header.getContext()
                )}
          </th>
        ))}
      </tr>
    ))}
  </thead>
  <tbody>
    {table.getRowModel().rows.map((row) => (
      <tr key={row.id}>
        {row.getVisibleCells().map((cell) => (
          <td
            key={cell.id}
            style={{ border: '1px solid black', padding: '8px' }}
          >
            {flexRender(cell.column.columnDef.cell, cell.getContext())}
          </td>
        ))}
      </tr>
    ))}
  </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode

8. Rendering the Chart
To visualize our sales data, we render the CanvasJS chart using the configured options. This step brings the multi-series bar chart to the screen, displaying product sales across quarters. Note that this needs to be added above the table in the JSX, as shown in the code:

<h2>Quarterly Sales Performance by Product</h2>
<CanvasJSChart options={options} />
Enter fullscreen mode Exit fullscreen mode

9. Component Structure

return (
  <div>
    <h2>Quarterly Sales Performance by Product</h2>
    <CanvasJSChart options={options} />
    <table>...</table>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Conclusion:
This example showcases the seamless integration of @tanstack/react-table and CanvasJS to present sales data in a React application. The table delivers a detailed, row-by-row breakdown of the numbers, while the multi-series chart offers a striking visual comparison of sales trends across products and quarters. The power of this setup lies in its flexibility—you can easily extend it with features like sorting, filtering, or alternative chart types (think line or area charts) to fit your specific needs. Take it further by adding custom styling for a polished look or enhancing interactivity with tooltips that reveal detailed data on hover. Experiment with this code, tweak it for your own datasets, and unlock the potential of dynamic, impactful data visualization!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (1)

Collapse
 
kelvincode1234 profile image
Precious Kelvin Nwaogu

Very Practical!!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay