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

The React Native application unexpectedly shuts down upon clicking on the RNPickerSelect component

Looking to populate a React Native dropdown (RNPickerSelect) with data, I implemented the following code: let year = new Date().getFullYear() - 4; let Years = [] for (var i = 0; i < 7; i++) { let item = { id: ...

Implementing Text Input Props in MUI: A Step-by-Step Guide

Hey there! I'm currently working on a text field that includes InputProps, specifically an icon that triggers an onClick event. <TextField id="outlined-basic" label="Type Tag Name" variant="outline ...

Assign a specific class to a table row once a checkbox is selected by utilizing states

I am working on a simple table within the parent component, where I pass props to the child component to create rows. My goal is to apply a specific style to rows when the checkbox is checked and remove it when unchecked. All checked rows should have this ...

How to Dynamically Update Sass Styles with Webpack 2?

Currently, I am in the process of setting up a React application that utilizes Webpack2, webpack-dev-middleware, and HMR for the development phase. One peculiar issue that I have encountered is related to updating .scss files. When I make changes to my .sc ...

What is the most efficient method for line wrapping in the react className attribute while utilizing Tailwind CSS with minimal impact on performance?

Is there a more efficient way to structure the className attribute when utilizing tailwind css? Which of the examples provided would have the least impact on performance? If I were to use an array for the classes and then join them together as shown in e ...

Padding and margin properties for Material UI Grid items and TextFields

I developed a standardized text input component for forms using Material UI and React-Hook-Forms. import Grid from "@mui/material/Grid"; import TextField from "@mui/material/TextField"; const inputSm = {xs: 12, sm: 12, md: 6, lg: 6, xl ...

Choose an element by its specific data attribute

I have come across this html code and I am attempting to assign a new class to it using the data attribute: <p class="form-row form-row-wide" data-child-field="child_has_jacket"> </p> Even after trying with jQuery : jQuery( ...

What is the functionality behind a free hosting website?

Is anyone familiar with websites like Hostinghood, where users can create a subdomain and upload HTML, CSS, etc.? I'm curious about how they operate and how I can create a similar site. This is my first question here, so please respond instead of disl ...

How can I display only the y-axis values and hide the default y-axis line in react-chartjs-2?

Although I have some experience with chartjs, I am struggling to figure out how to hide the default line. To clarify, I have attached an image that illustrates the issue. I would like to achieve a result similar to this example: . My goal is to make it loo ...

Having trouble deploying a Node/React application on Heroku

I've exhausted all of my troubleshooting methods and conducted extensive searches on Google. I have already eliminated common issues (such as not using process.env.PORT in app.listen). Below are the logs from Heroku: 2018-07-18T02:43:26.705491+00:00 ...

Tips for adjusting the width of a table

add your image description hereImagine a scenario where there is a table featuring two columns. <table> <tr><td>Email</td> <td></td></tr> <tr><td>Full name</td> <td></td></tr> ...

Tips for extracting data from nested JSON structures

I'm trying to retrieve the username of a user from the Firebase Realtime Database, which is stored in a UsersList. I have attempted various methods as shown in the code snippets below: https://i.stack.imgur.com/GsovS.png However, no matter what I tr ...

Why does the data in useState only update after clicking the button for the second time?

When utilizing useState to set a value, I noticed that it only updates upon clicking the button for the second time. Why does this occur? const DropDownMenu = ({ element, segmentEnd, segmentStart }) => { const [open, setOpen] = React.useState(false); ...

Alternatives to using $.getJSON()

When utilizing jQuery within the React/Redux environment, what alternative library is typically used for handling straightforward REST calls instead of $.getJSON or $.postJSON? Is there a widely-used option that functions similarly to node's http mod ...

The issue with text color not displaying properly within a Material-UI Theme

While designing a color theme using Material-UI, I specified the contrast text as white (#fff). Surprisingly, it seems to work for buttons with the primary color but not for those with the secondary color. I attempted overrides following the suggestions p ...

The forEach method is supported on FileList in CRA/Next JS applications, however, it does not work on FileList in Next JS applications created using

I've encountered a puzzling issue. While using forEach on a FileList in a website created with CRA and then migrated to Next JS, the code runs smoothly. However, when I recreated the website using create-next-app, forEach doesn't work on the file ...

React: Enzyme lacks functional local scope

As a React user, I recently implemented a basic redux counter using redux-toolkit. Testing is new to me, and I am currently utilizing Enzyme and Jest for testing purposes. The initial state of my redux counter is set to 1. During testing, within the it sco ...

CSS menu LI with horizontal spacing

I'm currently working on aligning the boxes for each <li> tag next to each other without any spaces in between. However, at the moment, there is a significant gap separating each box. How can I eliminate this space? Here is the HTML code snippe ...

"Encountering an error with AWS Amplify, Next.JS, and GraphQL Server: Unable to retrieve current user in

I'm encountering an issue with accessing data from Amplify's API Graphql, as it consistently returns Server Error Error: No current user I've been referring to this tutorial: https://youtu.be/13nYLmjZ0Ys?t=2292 Even though I have successfu ...

Npm issue. I'm unable to successfully install any packages as it keeps throwing an error

Issue: Error Encountered: Windows_NT 6.1.7601 Error occurred in the Windows_NT environment using the specified node and npm versions with error code EPEERINVALID. The package <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...