Tips for implementing styling in a material table within a reactjs application

  • Is there a different way to set the display property to inline-block since cellStyle doesn't seem to recognize it?
  • How can I adjust the width of a specific column, let's say with the name title, without affecting the width of all other columns?

Please Note:

The current solution works but I would like to add additional styling properties as well. Any suggestions on how to achieve this?


column.push({
  title: key,
  field: key,
  cellStyle: {
    backgroundColor: '#039be5',
    color: '#FFF',
  },
})
          

App.js


const MyComponent = () => {
    return (
        <div style={{ maxWidth: "100%" }}>
            <MaterialTable
                icons={tableIcons}
                columns={column}
                data={data}
                title="Demo Title"
                options={{
                    rowStyle: {
                       fontSize:10,
                      },
                    }}
            />
        </div>
    )
};

export default MyComponent
       

Answer №1

1. Creating Custom Styles using Props

To customize the style of a component based on props, move the column definition outside of the component and create it as a function that returns an array of objects. Then, in your JSX code, call this function while passing the necessary props or state.

2. Setting Custom Width

To set a custom width for a table column, use the tableLayout property in the options object and set it to fixed. Provide the desired width for each column in the columns array. Keep in mind that there is a known bug related to this feature, so monitor for updates. If your code breaks when the bug is fixed, refer to the issue resolution provided.

See Working Demo

Complete Code Snippet

const columns = propValue => [
  {
    title: "Avatar",
    field: "avatar",
    render: rowData => (
      <img
        style={{ height: 36, borderRadius: "50%" }}
        src={rowData.avatar}
        alt=""
      />
    ),
    cellStyle: {
      backgroundColor: "#039be5",
      color: "#FFF"
    },
    width: "40%" //<---- set width here
  },
  { title: "Id", field: "id" },
  { title: "First Name", field: "first_name" },
  {
    title: "Last Name",
    field: "last_name",
    cellStyle: {
      backgroundColor: "#039be5",
      color: "#FFF",
      display: propValue ? "inline-block" : "block"
    }
  }
];

class App extends Component {
  tableRef = React.createRef();
  propValue = true;

  render() {
    return (
      <div style={{ maxWidth: "100%" }}>
        <MaterialTable
          tableRef={this.tableRef}
          columns={columns(this.propValue)}
          data={query =>
            new Promise((resolve, reject) => {
              let url = "https://reqres.in/api/users?";
              url += "per_page=" + query.pageSize;
              url += "&page=" + (query.page + 1);
              fetch(url)
                .then(response => response.json())
                .then(result => {
                  resolve({
                    data: result.data,
                    page: result.page - 1,
                    totalCount: result.total
                  });
                });
            })
          }
          title="Remote Data Example"
          options={{ tableLayout: "fixed" }} // set table layout here
        />
        <button
          onClick={() => {
            this.tableRef.current.onQueryChange();
          }}
        >
          ok
        </button>
      </div>
    );
  }
}

NOTE: For material-table version 1.25 (or below), ensure to specify the column width inside the cellStyle object:

cellStyle: {
      backgroundColor: "#039be5",
      color: "#FFF",
      width: 10 //<----- define width like this
    },

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

Steps to keep the gridlines in the chart from moving

Take a look at the example provided in the following link: Labeling the axis with alphanumeric characters. In this particular instance, the gridlines adjust dynamically based on the coordinate values. How can we modify this so that the chart remains static ...

Varied elevations dependent on specific screen dimensions

There seems to be a minor issue with the height of the portfolio container divs at specific window widths. The problematic widths range from 1025 to 1041 and from 768 to 784. To visualize this, try resizing your browser window to these dimensions on the fo ...

Attempting to invoke setState on a Component before it has been mounted is not valid - tsx

I've searched through various threads regarding this issue, but none of them provided a solution that worked for me. Encountering the error: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a b ...

The app is opening the index.html file instead of the expected index.jsx file

After creating a page with React.jsx, I encountered an issue where my page was initially opening index.jsx upon running npm start. However, when I deleted and then restored the index.html file to "public", the page started opening index.html instead. This ...

Issues detected with Foundation Block Grid in small size setting

I created a React component to display a series of div elements on a page using the Foundation Block Grid system to control the number of divs per row. However, I am facing an issue where the number of divs does not change when switching to a small-sized s ...

What are some ways to monitor the movement of elements and activate functions at precise locations?

I am working on a project that involves a #ball element which, when clicked, utilizes jQuery animate to move downwards by 210px. The code I currently have is as follows: $('#ball').click(function() { $(this).animate({ top: '+=2 ...

Is the footer html/css duplicated on a different page and displaying differently?

I have been working on a website and just finished the main page with the header, body, and footer. Now, as I moved on to creating the second page, I encountered an issue. I copied and pasted the code for the header from the main page onto the second page ...

Which should I use - Angular directive or CSS selector, for better performance?

Currently expanding my knowledge on angular and exploring the capabilities of the ngClass directive. I have come across this interesting functionality: <li ng-repeat="language in languages" ng-class="{line:$even}">{{language}}</li> Alternativ ...

The width of the Ion-slide is dynamically determined by the styling

After transitioning my Ionic 2 project to Ionic 3, I encountered issues with ion-slides which are affecting my app's functionality. Upon app loading, specific widths are being defined in the style tags on the slides, disrupting the intended styling. ...

Is there a way to customize the background color of notistack in MUI v5?

The background color is currently set to white by default, but I am interested in changing it to a darker shade. In the mui v5 framework, dark mode can be enabled. While I have managed to change the error, info, and other variants, my main goal is to adj ...

Attempting to implement an EventListener to alter the navbar upon scrolling, unsuccessful at the moment

Exploring ways to update the navigation bar upon scrolling to shrink its size and modify the color scheme (specifically, transitioning from a transparent background to white and altering font colors). Below is the HTML snippet: /* Defining the overa ...

When testing, React does not trigger a rerender when a state change occurs

As part of my testing process, I am currently working on a React component that features a simple switch from Material-ui. This switch is designed to update a boolean field and functions properly when the application is run locally. During the testing pha ...

Typography is at the center of design

I'm having trouble centering the typography on my page using textAlign and align. Can anyone provide assistance with this? The code snippet below shows the solution I attempted: import React, {useState} from 'react' import logo fro ...

Is it permissible to utilize the ::Before::Before element?

While working on a CSS file for a page with a non-editable profile, I encountered the challenge of not being able to add content directly. This limitation prompted me to explore alternative solutions. My idea was to utilize the page ID and incorporate it ...

Timeout during page loading on Seleniumwebdriver

My automated test occasionally fails due to page load timeout. I have a suspicion that the issue may not be with the website itself, but rather with my test script manipulating the page. Here are some reasons why: Even when I adjust the page load timeout ...

Customizing the CSS of the TinyMCE editor within a React application

Incorporating TinyMCE 5 into my React project has been an interesting challenge. I'm looking to personalize the editor by adjusting elements like borders and adding box shadows to the toolbar. Despite attempting to add CSS through the content_css prop ...

Excessive spacing in the <td> elements - TABLE

I am encountering some problems with my table layout. The spacing between the field names and text boxes appears to be too large. Could there be mistakes I'm making that are causing this issue? How can I minimize the gaps? Please refer to the image b ...

What is the process for immediately changing the background color of an input field as soon as text is entered?

I am encountering an issue with the code snippet provided below. My goal is to change the background color of an input field as soon as I start typing something into it. The scenario involves 4 input fields where if the submit button is clicked and any f ...

Optimal Placement of CSS and index.html Files in ReactJS with Redux

Currently, my setup for the index.html file looks like this: <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Pra ...

Tips for modifying the color of selected text

Is there a way to change the color of the dropdown text? Currently, it is set to red but initially appears as black. When clicked on, it changes to red. How can I make it so that the color is initially displayed as red? <select> <option style ...