Modify the background color of column headers in a Material UI DataGrid as you scroll down vertically

In my React(NextJS) project using material UI, I have implemented tables (DataGrid component from material UI) with distinct background colors in the column headers, as shown below:

https://i.sstatic.net/zd3Iu.png

However, I encountered an issue where rapidly scrolling horizontally causes the colors to shift by 1 space/column. For example, the column "rank" should be yellow, but when scrolling quickly, it changes to red:

https://i.sstatic.net/du8C0.png

This sudden color shift by 1 space/column appears to be a potential bug in material UI, but I am uncertain...

Below is the code snippet of my React component:

// React component code here

Additionally, I utilize the "headerStyles" object as props, which contains the color configurations for each nth child/column:

// Header styles object here

If anyone has insights into why this issue occurs or how to resolve it, I would greatly appreciate the assistance.

Thank you.

Answer №1

When dealing with horizontal scrolling, relying on the nth-child styling may not be the most reliable approach. This is because the data grid virtualizes columns as you scroll horizontally, leading to not all columns being rendered at all times, causing disruptions in the nth-child styling.

An extreme example showcasing this issue can be seen in action here, with 30 columns and customized colors on the 3rd and 4th columns using nth-child CSS selectors: https://codesandbox.io/s/horizontal-scrolling-tlmqeh?file=/demo.tsx.

In the provided example, the styling is applied similarly to your CSS:

<DataGridPro
    sx={{
        "& .MuiDataGrid-columnHeader:nth-child(3)": {
            backgroundColor: "red",
            color: "#ffffff",
            fontWeight: "bold"
        },
        "& .MuiDataGrid-columnHeader:nth-child(4)": {
            backgroundColor: "purple",
            color: "#ffffff",
            fontWeight: "bold"
        }
    }}
    apiRef={apiRef}
    onCellClick={handleCellClick}
    hideFooter
    {...data}
/>

To address this issue, it is recommended to utilize the headerClassName in the column definitions, as outlined in the documentation here: https://mui.com/x/react-data-grid/style/#styling-column-headers.

Here is a modified version of the previous example that incorporates the use of headerClassName: https://codesandbox.io/s/horizontal-scrolling-087h4m?file=/demo.tsx

const { data } = useDemoData({
    dataSet: "Commodity",
    rowLength: 100
});
// data.columns[0] represents the hidden id column, while data.columns[1] is the first visible column definition.
data.columns[3].headerClassName = "red-header";
data.columns[4].headerClassName = "purple-header";

...

<DataGridPro
    sx={{
        "& .MuiDataGrid-columnHeader.red-header": {
            backgroundColor: "red",
            color: "#ffffff",
            fontWeight: "bold"
        },
        "& .MuiDataGrid-columnHeader.purple-header": {
            backgroundColor: "purple",
            color: "#ffffff",
            fontWeight: "bold"
        }
    }}
    apiRef={apiRef}
    onCellClick={handleCellClick}
    hideFooter
    {...data}
/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why are static PropTypes used in ReactJS and do they offer any solutions or are they merely a recurring design choice?

While delving into the code base of a web application, I came across some static PropTypes that left me questioning their purpose and necessity. Here is a snippet of the code in question: static propTypes = { fetchCricketFantasyPlayers: PropTypes.fun ...

Showing or hiding components within ReactJS based on conditions from other components

A custom hook has been created to toggle the visibility of a list when a button is clicked. Below is the snippet of the custom hook: import { useEffect } from "react"; import { useState } from "react"; function useVisibilityStatus() { ...

Bootswatch is causing the Bootstrap tooltip feature to malfunction

Could someone help me figure out why my tooltip isn't functioning properly? The HTML Code in Question: <div class="form-check"> <label class="form-check-label" > <input type="radio" class="form-check-input" name= ...

Incorporate React into current Node express application by utilizing a content delivery network (CD

I'm currently in the process of developing a web application utilizing both Node and React. Instead of having separate Node and React applications, I decided to integrate React directly into my existing setup. To achieve this, I attempted importing th ...

The navigation menu that usually appears on mobile devices is surfacing on desktop screens instead - update: images now

I have recently been working on my website juniorgoldreport.com, which was created using WordPress. The plugin I am using specifically for the mobile nav bar is The functionality and ease of use of this plugin are incredible. The setting to show the toolb ...

Issue with resizing Material UI avatar inside a card-like container

I'm hoping for some assistance with changing the Avatar size within my card component, but the code I have tried so far doesn't seem to be working. <Avatar alt="Remy Sharp" src="https://material-ui. ...

Animated CSS Checkmark Design

How can I create an animated Check-mark using CSS with SVG animation? I attempted the following code but it doesn't seem to be working. Any suggestions? DEMO: https://jsfiddle.net/b7Ln0jns/ CSS: @import "bourbon"; $color--green: #7ac142; $curve: c ...

Limit the results of the React API and explore additional items with the option to

For my page, I am working on conditional rendering to restrict the number of items a user can view in a component to 5. However, I also want to provide users with the option to see all items when they click on a 'more' button. I attempted to inc ...

"Optimizing Background Images with IE 8 Stretch Cover in Bootstrap

Page Broken I've searched all over Stack Overflow for a solution to resolve this background image issue. I'm using Bootstrap for the boxes and removed any margins. The problem arises when setting the background as cover; in IE8, it doesn't ...

Tips on utilizing CSS selectors with jQuery?

Is there a way to use jQuery to call a function on a web page load that will set the text "Hello world!" on all labels with the CSS class "hello"? I'm curious to learn more about how this works. Can anyone provide some insight? ...

Tips for maintaining the default arrow icon for HTML select elements

While styling a drop down in Firefox on Mac OS X, I noticed that the arrow changes from the standard look to an unattractive downward arrow. How can I maintain the standard form element with the appealing up and down arrows, instead of the unsightly downwa ...

Emphasize rows in the MUI-Datatables framework

A table was created using React.js and MUI-Datatables: import MUIDataTable from "mui-datatables"; const columns = ["Name", "Company", "City", "State"]; const data = [ ["Joe James", "Test Corp", "Yonkers", "NY"], ["John Walsh", "Test Corp", "Hartford", ...

Sending data from a React application to a Node.js server using Axios

Hello, I am facing an issue with an axios request to post data to a Node.js server. When trying to access this data on the server, it is showing as undefined. Below is the function for posting data: function Submit() { let params={ firstName: ...

What is the correct way to write the syntax for wp_register_style function in

I'm attempting to include a cache-buster version in my CSS file. The guides mention: <?php wp_register_style( $handle, $src, $deps, $ver, $media ); ?> However, I've scoured Google and Stack Overflow for the correct formatting of these var ...

Exploring Next.js: A Guide to Implementing Browsing History in Your Application

Struggling to add entries to browser history when using Next.js's Link property for page navigation. Unable to push history entry, leading to incorrect page location in my application when going back. Any ideas on implementing this feature in Next.js? ...

Customizing Pie Legends in Echart Configuration

I am trying to find a way to present pie chart legends along with their values in a unique format. I have attached an image for reference. Despite my efforts, I haven't been able to figure out how to achieve this specific display. If you take a look a ...

Troubleshoot: Font Rendering Issue with CSS3 @font-face in Opera 11.x

Having some trouble with Opera not displaying my HTML5 site correctly. Everything looks good in Safari, Chrome, IE9, Firefox 3.5+ and more. Wondering if anyone has encountered this before and found a solution. Here's the breakdown of my setup: In the ...

Can material-ui codemod v5 be implemented in a project that utilizes flow types?

I am looking to transition from material-ui v4 to v5. When I try to use the codemode with: npx @mui/codemod v5.0.0/preset-safe . it is not working for me, especially in files where flowjs types are declared like this: (which applies to all my files) type ...

Ways to conceal the current state changes from being displayed in the URL

I've implemented a React form with text fields and radio buttons to store data in the state. The 'Proceed' button triggers an onClick function: handleClick(event){ console.log(this.state); var userID = 1; firebase.database().ref ...

Struggling with Adding Column Filtering to TanStack/shadcnUI React Table

I am currently in the process of working on a project that involves implementing the TanStack/shadcnUI React Table for creating a data grid with filtering capabilities. However, I have run into an issue where the column filter does not seem to be functioni ...