Articles in this section
Category / Section

How to position the columns in a React Pivot Table according to the current year and its quarter?

5 mins read

Introduction

When working with React Pivot Table, there may be scenarios where you initially need to display columns pertaining to the current year and its quarter. This feature enhances the user experience by immediately showcasing relevant time-based data. The following code snippet demonstrates how to implement this functionality by identifying the column index corresponding to the current year and quarter and then programmatically adjusting the horizontal scroll position accordingly.

Identify the column index for the current year and its quarter

In order to obtain the column index, you need to use the headerCellInfo event in your code. This event is triggered during the rendering of each column header cell in a pivot table and enables you to find the index of a specific column. Below is a code example that demonstrates how to identify the column index that represents the current year and its quarter.

[index.js]

import { PivotViewComponent } from '@syncfusion/ej2-react-pivotview';

let count = 0; // Tracks the column index position of the current year and quarter.
let isInitial = true; // A flag to ensure scroll position is set only during the initial render.
let currentYearFlag = false; // Used to stop counting once the current year and quarter column is found.

// Get the current date
const currentDate = new Date();
// Get the current year from the current date
const currentYear = currentDate.getFullYear();
// Get the current month (0-indexed, so January is 0 and December is 11)
const currentMonth = currentDate.getMonth();
// Calculate the current quarter
const currentQuarter = Math.floor(currentMonth / 3) + 1;
let currentYearWithQuarter = currentYear + "-Q" + currentQuarter;

function Default() {
    let pivotObj;
    function headerCellInfo(args){
        // Here, get the column index of the current year and quarter.
        if(pivotObj  && !currentYearFlag && args.node.innerText !== "") {
            count++;
            // Once we obtained the column position of the current year, we stopped increasing the count variable.
            if(args.node.innerText == currentYearWithQuarter){
                currentYearFlag = true;
            }
        }
    } 

    return (
            <PivotViewComponent id='PivotView' ref={(scope) => { pivotObj = scope; }} 
		gridSettings={{ columnWidth: 140, headerCellInfo: headerCellInfo }}>
            </PivotViewComponent>);
}
export default Default;
Here’s a breakdown of how the code works:
  1. First, we initialize two variables named “count” and “currentYearFlag”. The ‘count’ variable is used to track the column index for the current year and its quarter as we iterate through header cells in a pivot table. Meanwhile, “currentYearFlag” is a boolean variable that stops the ‘count’ variable from increasing once the current year and its quarter are identified.
  2. Following this, we obtain the current date, extract the current year and month, and then calculate the quarter based on the current month.
  3. Afterward, we create a string representation “currentYearFlag” that combines the current year and the quarter in the format Year-Quarter.
  4. Then, within the headerCellInfo event, we check if the pivot object exists, if the flag (i.e., “currentYearFlag”) for identifying the current year and quarter remains false, and if the cell’s inner text is not empty. If these conditions are met, we increment the “count” to keep track of the column index.
  5. Finally, we check whether the text within each header cell (args.node.innerText) matches the “currentYearWithQuarter” variable. If there is a match, the “currentYearFlag” is set to true. This signifies that the column representing the current year and quarter has been identified and that the “count” will not increase for subsequent columns.

Adjust the horizontal scroll position of the Pivot Table

After identifying the column index for the current year and its quarter, you need to use the dataBound event in your code. This event is triggered when the pivot table is either rendered or refreshed. It allows you to adjust the horizontal scrolling position of the pivot table to initially show the columns related to the current year and its quarter.

[index.js]

import { PivotViewComponent } from '@syncfusion/ej2-react-pivotview';

let isInitial = true; // A flag to ensure scroll position is set only during the initial render.

function Default() {
    let pivotObj;
	function dataBound() {
		if (pivotObj && pivotObj.element.querySelector('.e-content') && isInitial && pivotObj.element.offsetHeight > 200) {
		    isInitial = false;
		    var scrollBar = pivotObj.element.querySelector('.e-content');
		    // Here we calculate required scroll width
		    var width = pivotObj.gridSettings.columnWidth * ((count-1)* pivotObj.dataSourceSettings.values.length);
		    scrollBar.scrollLeft = width;
		}
	}

    return (
            <PivotViewComponent id='PivotView' ref={(scope) => { pivotObj = scope; }} 
		gridSettings={{ columnWidth: 140,headerCellInfo: headerCellInfo }} dataBound={dataBound}>
            </PivotViewComponent>);
}
export default Default;
Here’s a breakdown of how the code works:
  1. First, we initialize a boolean variable “isInitial” to ensure that the scrolling action is executed only once during the initial rendering process.
  2. Then, within the dataBound event, we check if the pivotObj object exists and its content is correctly loaded. Additionally, we verify if the pivot table height exceeds a certain limit (i.e., 200px). Once the conditions are met, the “isInitial” flag is set to false to prevent this code from running multiple times unnecessarily.
  3. Following this, we calculate the required scroll width to bring the current year and quarter column into view. This can be achieved by multiplying the column width (i.e., pivotObj.gridSettings.columnWidth) by the total number of columns up to the target, which can be calculated as (count-1) * pivotObj.dataSourceSettings.values.length.
  4. Finally, the calculated width is assigned to the scroll left property of the scrollbar (i.e., scrollBar.scrollLeft). This process automatically scrolls the content of the pivot table horizontally, thereby displaying the columns for the current year and its corresponding quarter (i.e., 2024-Q1).

The following screenshots images portray the difference between before and after implementing the above workaround solution:

Screenshots
Before implementing the workaround solution,

KB-15568-Before.png

After implementing the workaround solution,

KB-15568-After.png

For a practical example of this code in action, you can refer to the following sample of stackblitz.

Conclusion

I hope you enjoyed learning how to position the columns in a React Pivot Table according to the current year and its quarter.

You can refer to our React Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Pivot Table example to understand how to create and manipulate data.

For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied