What is the process for implementing CSS on the header of a Material UI Table with stickyHeader functionality?

I've implemented a Material UI table with the stickyHeader prop to keep the header fixed. However, I'm facing an issue where other CSS styles are not being applied to the header section.

const useStyles = makeStyles((theme) => ({
    tableHead: {
        borderBottomStyle: "solid",
        borderBottomColor: "blue",
    },
}))

const CustomTable = () => {
    return(
        <TableContainer component={Paper} className={classes.tableContainer}>
            <Table stickyHeader aria-label="simple table">
                <TableHead classes={{ root: classes.tableHead }}>
                    <TableRow>
                        <TableCell>Hii</TableCell>
                    </TableRow>
                </TableHead>
            </Table>
        </TableContainer>
    )
}

After removing the "stickyHeader" prop, I can see the blue border at the bottom of the header. It seems like the border is not displaying when using stickyHeader.

Answer №1

After encountering the same issue with MUI 5, I found a solution for maintaining styling while using the stickyHeader prop on my <Table>.

I made adjustments to the MuiTableCell-root class within my TableHead component and everything worked smoothly.

Here's an example utilizing styled-components:

export const StyledTableHead = styled(TableHead)`
  & .MuiTableCell-root {
    background-color: red;
  }
`;

It seems that in order to make the stickyHeader prop work correctly, you need to set a maxHeight for the <Table> within the <TableContainer> first.

Here's another example with styled-components:

export const StyledTableContainer = styled(TableContainer)`
  border-top-left-radius: 0.3rem;
  border-top-right-radius: 0.3rem;
  max-height: 500px;
`;

You can implement this like so:

<StyledTableContainer>
  <Table stickyHeader>
    <StyledTableHead>
      <TableRow>
        [your table header cells here]
      </TableRow>
    </StyledTableHead>
  </Table>
</StyledTableContainer>

Answer №2

When the props stickyHeader are added, a class is automatically inserted that applies the style border-collapse: separate. To reveal the header border, this class must be removed.
The goal is to target the Mui class stickyHeader from the Table.

<TableContainer component={Paper} className={classes.tableContainer}>
    <Table stickyHeader classes={{stickyHeader:classes.stickyHeader}} aria-label="simple table">
        <TableHead classes={{ root: classes.tableHead }}>
            <TableRow>
                <TableCell>Hii</TableCell>
            </TableRow>
        </TableHead>
    </Table>
</TableContainer>
const useStyles = makeStyles((theme) => ({
    tableHead: {
        borderBottomStyle: "solid",
        borderBottomColor: "blue"
    },
    stickyHeader:{
        borderCollapse:'collapse'
    }
}));

Update

To ensure the border remains fixed, a simple workaround is to add a borderBottom style in the TableCell of the TableHead.

<Table stickyHeader aria-label="simple table">
    <TableHead>
        <TableRow>
            <TableCell
                style={{
                    borderBottom: "5px solid blue"
                }}
            >
                Hii
            </TableCell>
        </TableRow>
    </TableHead>
    <TableBody>
        {//Tablebody items}
    </TableBody>
</Table>

See a working demo here:
https://codesandbox.io/s/gallant-euler-5p4rn?fontsize=14&hidenavigation=1&theme=dark

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

The collapsing menu is malfunctioning due to duplicate selectors

Although I have been learning HTML, CSS and jQuery, one area that always trips me up is selectors. Currently struggling with redundant selectors. I am attempting to customize the ul and li elements after collapsing the li, however, the selector doesn&apos ...

useEffect: dependency list doesn't stop continuous rerenders

I am facing an issue with my useEffect hook that has a dependency array. Despite my logic being straightforward - fetching data for tuition, then adding it to the program object in the programData array - I can't figure out why it keeps triggering re- ...

"Embracing the power of dynamic CSS customization within Umbraco

I recently inherited an Umbraco system without much prior knowledge of the platform, and I am currently investigating the site's performance. The branding and styling of the site is currently managed through a "Brand" document type, allowing the site ...

Organizing data with JavaScript: Transforming a flat array into nested JSON structures

In my front-end TypeScript file, there is a list called poMonths: 0: {id: 1, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-12-15T00:00:00", purchaseMonthString: "Dec-2019" , year: 2019, month: "December"} 1: {id: 2, company ...

Connect ng-models with checkboxes in input field

I am facing an issue with binding ng-models using ng-repeat in an input checkbox tag. Let me share my code and elaborate further. app/main.html: <div ng-repeat="feature in features"> <input type="checkbox" ng-model="features[$index].name"> ...

Is it possible to use jQuery for drag-and-drop functionality?

Currently, I am working on developing a drag-and-drop widget that consists of 3 questions and corresponding answers. The user should only be able to fill in 2 answers in any order, while the third drop area should be disabled. This third drop area can be l ...

Encountering a JavaScript/TypeScript issue that reads "Unable to access property 'Items' as it is undefined"

I encountered an issue with Javascript where I'm receiving an error message stating "Cannot read property 'Items' of undefined". The this keyword is consistently showing as undefined in the Base class. How can this problem be resolved? Coul ...

Error encountered after attempting to save with incorrect configuration settings for the resource

A portion of my code involves a service module that sends data using the POST method: //services.js var myServices = angular.module('myServices', ['ngResource']); myServices.factory('User', ['$resource', function($ ...

Launch a modal by clicking a button located in a separate component using Vue JS

I am dealing with 2 components: TestSearchTool and TestModal. My goal is to display the Modal when a button in the TestSearchTool component is clicked. These two components are siblings in the hierarchy, so I am struggling to pass values between them (even ...

Styling is not being applied to the DataTable when it is invoked through an ajax

I have developed a simple SpringBoot application using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and packaged it as an executable JAR file. Within this application, I have implemented two datatables: one utilizing ajax and the ot ...

Causing a click event to occur results in crashing the browser

Take a look at this link: example on jsfiddle Why does the click event keep triggering multiple times when a div is clicked, eventually causing the browser to crash? What could be causing this issue and how can it be resolved? The actual div contains a l ...

Using React with Identity Server 4

Can anyone provide assistance with this issue I'm facing? I followed the instructions in a tutorial to create a new dotnet app using dotnet new react --auth Individual -o. Authentication is working well, but now I want to customize the layout of the l ...

The countdown timer resets upon the conditions being rendered

I have been using the 'react-timer-hook' package to create stopwatches for each order added to an array. The problem I encountered was that every stopwatch, across all components, would reset to zero and I couldn't figure out why. After a lo ...

ng-option featuring a stationary link option

How can I create a static option that links to another page using ng-options? <select class="form-control" ng-model="person" ng-options="person.name for person in persons"> </select> I am trying to use the select element with ...

Display a loading splash screen prior to loading Next.js

I am working on a NextJS website and I'm looking to incorporate a Splash Screen that displays before the site is fully loaded. However, since the Splash Screen is included in the NextJS code, it ends up loading after NextJS has rendered on the server ...

Module loader.js not found by Next.js

Whenever I attempt to execute the command npm run dev, an error occurs. I have attempted troubleshooting by deleting the package-lock.json and node_modules, as well as reinstalling npm, but none of these solutions have resolved the issue. PS D:\Users ...

Turn off and then reinstall Image when clicked

function show(){ alert("i am pixel"); } function disableImgClick(){ $(".Dicon").unbind('click'); } $(document).ready(function(){ $("#turnoff_btn").click(function (e){ e.preventDefault(); disableImgClick(); }); }); i have a group of ima ...

Learn how to create a stunning effect by combining two half images and revealing a full image upon hover with a smooth animation

I am struggling with implementing a specific feature using jQuery. I have designed a page hero with two sections (red and black): My goal is to have the black section expand over the red section when hovering, creating a full black box. I want the same ef ...

Enhancing CSS with Additional Properties

As a web developer, I recently had the opportunity to explore the new LOGIN PAGE preview of GMAIL and was very impressed with the Sign In button's UI. After examining the Page's CSS, I discovered some interesting properties, such as: **backgroun ...

Attempted to utilize zipstatic but received no feedback

I attempted to utilize the Zipstatic API with jQuery in my code, as shown below. However, I am not receiving any response. Could there be something missing? jQuery(function() { jQuery("#form").hide(); jQuery("#postcode").keyup(function() { var c ...