Trouble aligning Material UI data-table columns (table head) to center in React

I have a data table where I declare rows and columns as simple variables, making it difficult to style them using 'style={{textAlign: center}}'. I tried adding a CSS file, but it did not work with the Material UI table. I am unsure of how to proceed. Here is my code:

import * as React from 'react';
import { DataGrid } from '@material-ui/data-grid';

export default function DataTable({data, someColumns}) {

    const columns = someColumns;
      
    const rows = data;

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid rows={rows} columns={columns} pageSize={5} checkboxSelection />
    </div>
  );
}

The data in the columns defaults to being aligned left. How can I change this?

EDIT: I was able to fix it using this CSS. Thanks to Fahad.

.MuiDataGrid-colCellTitle {
    display: block;
    text-align:center;
    width: 100%; 
}

.MuiDataGrid-cell {
    display: block;
    position: relative;
    text-align: center;
}

This CSS will center both rows and columns in the table.

Answer №1

If you happen to stumble upon this issue, I recommend checking out the implementation of ColDef linked here.

The recommended way to approach this is as follows:

const [columns, setColumns] = useState([
  {
    field: 'status',
    width: 130,
    headerName: 'Status',
    // Set text alignment properties for headers and cells
    headerAlign: 'center',
    align: 'center',
    renderCell: (params) => {
      return (
          <Chip label={params.value} />
      )
    }
  },
]);

If your content includes elements other than text (as shown in the example), simply setting alignment properties might not center the content properly. Since cells are styled with display: flex and align-items: center, you'll need to add justify-content for horizontally centered cells:

.MuiDataGrid-cellCenter {
  justify-content: center;
}

You can apply similar adjustments for MuiDataGrid-cellLeft or MuiDataGrid-cellRight if required.

Answer №2

I found a solution that worked perfectly for me.

If you want to target th and tr in your style.css file, you can do so using the property .MuiDataGrid-colCellTitle. To align it in the center, add the following CSS:

Style.css

 .MuiDataGrid-colCellTitle {
  display: block;
  text-align:center;
  width: 100%;
}

Make sure to import the necessary components:

import { DataGrid } from '@material-ui/data-grid';

Next, declare your rows and columns data within a function:

export default function DataGridDemo() {
  const columns = [
    // Add your column data here
  ];

  const rows = [
    // Add your row data here
  ];
  
  // Apply your styles

  return (
    <div
      style={{
        height: 400,
        width: "100%",
        backgroundColor: "red",
        textAlign: "center"
      }}
    >
      <DataGrid rows={rows} columns={columns} pageSize={5} checkboxSelection />
    </div>
  );
}

You can find the Code Sandbox link with an example implementation here: https://codesandbox.io/s/thirsty-leaf-izuhd?file=/src/App.js

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

Changing the height of tablerows in Material UI v5: A step-by-step guide

I am attempting to adjust the height of the rows in this material-ui code example. import * as React from "react"; import { styled } from "@mui/material/styles"; import Table from "@mui/material/Table"; import ...

Creating a QR code alongside an image positioned in the center: Step-by-step guide

Is there a way to create a QR code using react js or node js? I'm looking for a library or package that can generate a QR code with an image in the center. Do you know of any options? For example: ...

Can an API call continue running server-side without interruption if I redirect to another page in React?

After using the post method to send data through an API call to Node.js and receiving a response, another API will be triggered. Even if the user decides to visit another page at that moment, the API calls will continue to run without being aborted. ...

Creating a Post API in React using the useState Hook

Currently, I am developing a Mern-stack Application that incorporates Material-UI. My application involves an Event model, which in turn has multiple comments associated with it. The main challenge I am encountering at the moment is how to post a comment ...

Next.js encountered an error when trying to locate the 'net' module while working with PostgreSQL

I'm facing a challenge in my Next.js project while attempting to retrieve all records from a table. The error message I'm encountering is "Module not found: Can't resolve 'net'" with an import trace pointing to multiple files withi ...

What steps should I take to correct the alignment of this grid using CSS?

I'm currently working on creating a grid layout for my website and I've almost achieved the desired result. However, I'm facing an issue with the size of the "Projects" title within the grid. I want it to stand out and be larger compared to ...

What is the best way to ensure that two contact fields are capable of adapting

Looking for a way to center two fields ("Call Us" and "Our Email") while also ensuring they are responsive on different screen sizes? The goal is to have them stack one on top of the other when viewed on a small screen. Even though inline CSS has been used ...

Customized placement of form fields on an HTML grid determined by the user

My goal is to organize input elements on a grid based on user preferences. After researching, I stumbled upon CSS grids, which seem promising. I am considering creating a CSS grid with r rows and c columns, then using JavaScript to assign input elements t ...

Is there a way to insert images from a webpage in NextJs?

I am encountering issues while trying to incorporate the Coloplast logo into my project using this URL(https://www.coloplast.com/Global/1_Corporate_website/Press/Pics/CPlogo_Gray_RGB_300.png). **Unfortunately, I keep getting this error message ** Server ...

Styling with CSS in Angular 2+ can be quite challenging

Hey there, I'm new to Angular 4 and running into some troubles with styling my application. I tried adding a background image to the body, which worked fine, and then added a component to display content, also looking good. Now, when I added a second ...

Guide to positioning Navigation Bar in the center

I'm currently in the process of updating my website, but I've encountered a problem that I can't seem to solve. The issue revolves around the positioning of my navigation bar. Currently, it is situated below some JavaScript content and on t ...

Is it possible to conceal the Google recaptcha badge using CSS and show the legal text in its place instead?

We have successfully hidden the Google reCaptcha badge on our website using CSS: <style> .grecaptcha-badge { visibility: hidden; } </style> As a result, there is now an empty space where the reCaptcha badge used to be display ...

Tips for dividing the WordPress header navigation horizontally using separate PHP files

I am trying to customize my WordPress menu navigation by splitting it into two sections: left and right. I have added the menu function in the "functions.php" file to create the menu from the backend, and the frontend modifications will be done in the "hea ...

Are there any aesthetically pleasing CSS themes available for GWT integration?

This inquiry has been raised in the past... GWT 2.0 Themes? GWT Themes and Component Libraries ...however, two years have elapsed. Previously, the response was mainly negative unless utilizing a widget library. I am on the lookout for an appealing CSS ...

Selector for the Nth child element

Struggling with the nth child selector. Here is the HTML snippet: HTML <div class="container"> <ul class="mh-menu"> <li> <a href="#"> <span>Chairman of the Board</span> <spa ...

Why do I always find myself needing to verify variable values in react?

When working with React, I sometimes encounter the profile is null error upon page refresh. To address this issue, I have resorted to enclosing all the code inside if statements like so: useEffect(() => { getCurrentProfile(); if(user && ...

Adjusting the border size of an SVG without using the viewbox

Currently, I am working with 2 SVGs where one has a viewbox and the other doesn't. They both are set to be 100% width of the parent element. The first SVG scales according to its viewbox while the second one scales according to the height of the paren ...

Click the button to go to the initial page on the pagination bar of a material-ui

I am currently working with the react material-ui tables component and I am looking for a way to improve pagination by adding options to load both the first and last pages, or setting a list of all available pages in the table pagination. Any suggestions ...

Ways to stop the thead from appearing on every page in a printout

Is there a way to prevent the thead of a table in an HTML page from being printed on all pages when a user initiates printing? The issue arises because I am using page-break-after: always; on an element before my table, causing the table header to also be ...

Monitoring active users on Django platform using rest framework

I successfully implemented the functionality of retrieving online users using django-online-users. However, I am facing an issue with getting online users in Django Rest Framework when users make API calls from React to the backend server. Currently, I ca ...