"Aligning the title of a table at the center using React material

I have integrated material-table into my react project and am facing an issue with centering the table title. Here is a live example on codesandbox:

https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js

I specifically want to center the title "Average Expense ratio", as shown in this image:

https://i.stack.imgur.com/ujLER.png

I attempted to add the style prop textAlign:"center" to the MaterialTable but it didn't work. Is there a way to achieve this?

Answer №1

If necessary, you can customize the Toolbar component and incorporate a personalized title React component.

import "./styles.css";
import MaterialTable, { MTableToolbar } from "material-table";
import Typography from "@material-ui/core/Typography";

const CustomTitle = ({ text, variant }) => (
  <Typography
    variant={variant}
    style={{
      whiteSpace: "nowrap",
      overflow: "hidden",
      textOverflow: "ellipsis"
    }}
  >
    {text}
  </Typography>
);
export default function App() {
  const softRed = "#CC6666";

  //GREENS

  const forestgreen = "#556B2F";
  const limegreen = "#228B22";
  const lightgreen = "#3CB371";

  //ORANGES
  const softOrange = "#ffd27f";

  return (
    <div className="App">
      <MaterialTable
        style={{}}
        title={<CustomTitle variant="h6" text="Average Expense Ratio" />}
        components={{
          Toolbar: (props) => (
            <div
              style={{
                alignItems: "center",
                justifyContent: "center",
                display: "flex"
              }}
            >
              <MTableToolbar {...props} />
            </div>
          )
        }}
        columns={[
          {
            title: "0.19 and below",
            field: "first",

            headerStyle: {
              backgroundColor: forestgreen
            }
          },
          {
            title: "0.20 to 0.48",
            field: "first",
            headerStyle: {
              backgroundColor: limegreen
            }
          },
          {
            title: "0.49 to 0.77",
            field: "first",
            headerStyle: {
              backgroundColor: lightgreen
            }
          },
          {
            title: "0.78 to 1.06",
            field: "first",
            headerStyle: {
              backgroundColor: softOrange
            }
          },
          {
            title: "1.07 and above",
            field: "first",
            headerStyle: {
              backgroundColor: softRed
            }
          }
        ]}
        data={[]}
        options={{
          headerStyle: {
            color: "#FFF",
            textAlign: "center",
            whiteSpace: "nowrap",
            fontSize: 10
          },

          paging: false,
          search: false,
          sorting: false,
          showEmptyDataSourceMessage: false
        }}
      />
    </div>
  );
}

https://i.stack.imgur.com/LJibg.png

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

Input fields in Next.js are experiencing issues with undefined props

Having some trouble creating a SearchBar feature that updates the "value" prop with user input. Struggling with getting the value and changeInput props to work properly, they keep returning as undefined. Any assistance would be greatly appreciated! cons ...

What is the best way to stop event bubbling in react-router-dom when using the <Link> component?

Hey there! I have a situation that I need help with. I tried putting the Link around the whole post so that I could prevent bubbling for individual buttons, but for some reason stopPropagation() is not working as intended. Following advice from another s ...

Utilizing Node.js for Gmail API: Extracting Inline/Embedded Images

When working with email data, one approach is to use the gmail.users.messages.get() method. After fetching the email data, there are two functions used to handle the payload. function getBody(message) { var encodedBody = ''; try{ i ...

What causes old data to linger in component and how to effectively clear it out

Fetching data from NGXS state involves multiple steps. First, we define the state with a default list and loading indicator: @State<CollectionsStateModel>({ name: 'collections', defaults: { collectionList: [], (...), isListLoading: true, ...

Effortlessly passing props between components using React TypeScript 16.8 with the help

In this scenario, the component is loaded as one of the routes. I have defined the type of companyName as a string within the AppProps type and then specified the type to the component using <AppProps>. Later on, I used {companyName} in the HTML rend ...

Show a specific form field based on the chosen option in a dropdown menu using Angular and TypeScript

I am looking to dynamically display a form field based on the selected value from a dropdown list. For instance, if 'first' is chosen in the dropdown list, I want the form to remain unchanged. However, if 'two' is selected in the drop ...

Using @emotion/styled alongside esbuild has caused an issue where importing styled11 as default.div is not functioning as expected

Working on building a website using esbuild, react, and emotion/MUI has been smooth sailing so far. However, I've hit a roadblock with getting the styled component from @emotion/styled to function properly. uncaught TypeError: import_styled11.default ...

Optimizing Firebase and Next.js for serverless deployment on Google Cloud Platform: A guide to effectively managing staging, production, and

Currently, I am utilizing React along with next.js and Google Cloud functions to host my application. Additionally, I am integrating firebase into the mix. One pressing issue I am facing pertains to efficiently configuring the staging and production enviro ...

Display the Material UI Switch in an active state even when the "checked" value is set to false

While using Material UI Switches with Formik, I've encountered an issue. When I toggle the switch to 'enable,' it automatically sets the value in Formik to "true," and when I toggle it to 'disable,' it sets the value in Formik to " ...

How to vertically align Material UI ListItemSecondaryAction in a ListItem

I encountered an issue with @material-ui/core while trying to create a ListItem with Action. I am looking for a way to ensure that the ListItemSecondaryAction stays on top like ListItemAvatar when the secondary text becomes longer. Is there any solution to ...

What is the best way to determine total revenue by consolidating data from various tables within an IndexedDB database?

Seeking guidance on building a stock/sales application in JavaScript with Dexie.js. I need assistance in efficiently calculating the Total Sales amount without resorting to overly complicated recursive code that triggers multiple queries for a single produ ...

Block-level declarations are commonly used in TypeScript and Asp.net MVC 5

In my asp.net mvc5 project, I decided to incorporate TypeScript. I created an app.ts file and installed the nuget-package jquery.TypeScript.DefinitelyTyped. Here is a snippet of the app.ts code: /// <reference path="typings/jquery/jquery.d.ts"/> cl ...

Updating Array Values in AngularJS based on Input Text Box Modifications

In my application, there is a text box that looks like this - <input type="text" class="form-control" id="inputID" name="ItemId" ng-model="inputItemId" ng-required="true" ng-blur="addValueToArray(inputItemId)"/> The user has the ability to add or r ...

Tips for adding responses to input fields in AngularJS

I am looking to populate data into 3 inputs based on the JSON response I receive from my node server. However, despite receiving a response, I am unable to input it into the designated fields. Controller: $scope.edit = function(id, contact) { console.log ...

Get rid of the TypeScript error in the specified function

I am currently working on implementing a "Clear" button for a select element that will reset the value to its default state. Here is a snippet of my code: const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => { onChange( ...

The error is popping up as I try to deploy my Next.js application on Vercel

warning " > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d0f181c1e095009120d5011121c1914131a501f1c0f3d4f534c534d">[email protected]</a>" has an incorrect peer dependency "react@^16 || ^17" ...

The art of aligning Material UI Grid elements

Is there a way to vertically align items in Material UI effectively? Check out this code sandbox example for reference. In my project, I aim to position the Start element at the top, Center element in the middle, and the End element at the bottom ...

How come I am getting the desired section from my split string only after running the function twice?

I've been working on a function that retrieves data from a form and sends it to a POST request, which in turn sends it to my MongoDB database. The following code snippet showcases the process of uploading an image to IPFS, extracting the IPFS hash fro ...

Enhance Bootstrap typeahead to accommodate multiple values

I have a basic typeahead setup for searching city names. However, upon selecting a city, I also need to retrieve its latitude and longitude in order to send that data to the backend. $('.typeahead').typeahead({ minLength : 3, source : ...

Avoid the CSS ::before content from being highlighted

I have implemented the ::before pseudo-element for my ordered and unordered lists in my application. However, I am facing an issue where only the ordered lists are highlightable, and I am unable to change the highlight color to match the overall look of my ...