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

Difficulty with Cross-Origin Resource Sharing (CORS) in React when attempting to make a

I've encountered a problem with my app. I'm using Express/node for the API and trying to access it with React, which is working well with Axios. However, when I attempted to use a DevExpress grid component to display data, fetching the data was ...

After selecting an item, the Next UI navbar menu seems to have trouble closing

Having trouble with the navbar menu component not closing when an option is selected from the menu. The menu does open and close successfully within the menu icon. I attempted to use onPress() but it doesn't seem to be working as expected. "use c ...

I currently have two responsive menus and I'm trying to figure out how to modify the javascript so that when one menu is opened, the other

I am facing an issue with my responsive menus on a webpage, similar to the example provided in the jsfiddle link below. Currently, when one menu is open and I click on another, both remain open. How can I modify the JavaScript code so that when one menu op ...

Step-by-step guide on arranging/placing/styling two div elements next to each other

I'm facing an issue with my CSS and HTML. I can't seem to get the 2 footer items to display on the same line. Is there a problem with how I've structured my divs and styles? Any suggestions for improving the code are greatly appreciated. I& ...

Incorporate a variable into a CSS class

Currently, I am working on developing a component that creates an animation loop with a duration that is passed as a prop to the component. The issue I am facing involves using CSS to create the animation: animate:{ -webkit-transition: 10.0s !important ...

What is the best way to use a computed property as a style value for a component in Vue.js?

My component's template includes the following HTML element: .grid-item(:style="{ width: columnWidth, backgroundColor: 'blue' }") I want to dynamically set the width of this element using a computed property: computed: { columnWidth () ...

What is the best way to rearrange images within a grid container?

I apologize for asking numerous questions, but could someone please guide me on how to position an image slightly to the right of center or just 1 inch to the left of center? http://jsfiddle.net/96d7udd7/ Below is the HTML code snippet: <figure class ...

Is it possible to create a fading effect on an image using a border-radius of 50%?

Struggling with fading out an image that's circular in shape due to the border-radius: 50%. <section id="main"> <h1>Non-Important-Text</h1> <h4> it's all fun and games until you can't find a damn sol ...

I am experiencing an issue with my Material UI button not displaying and failing to render any content on my web application

Utilizing Material UI for buttons in my web app using ReactJS for the frontend has been a bit challenging. After installing Material UI with the command: npm install @material-ui/core My code appears as follows: import React from 'react'; import ...

React's behavior with Socket.io becomes unpredictable after sending five messages

I'm facing a strange issue while trying to develop a basic chat application using socket.io and React. The application functions as expected for the first 5 messages, but from the 6th message onwards, there is a delay in loading and sometimes previous ...

What is the best way to calculate the overall number of comments per post when using node.js, react js, and sequelize?

Currently, I am working on a project that allows users to ask and answer questions. However, I am facing an issue with the comments field. The comments table displays data correctly and can delete entries, but I need to find a way to count the total number ...

Is it possible to implement formvalidation.io in a React project that is using Materialize-css?

Can the formvalidation.io plugin be used with React and Materialize-css in a project? My project consists of multiple input components that may or may not be within a form. I want to utilize formvalidation for input validation. However, I am unable to find ...

Having trouble displaying one DIV above another DIV

I'm having trouble getting an image in a DIV to display above text in another DIV. I can't figure out why it's only displaying below. <div> <div style='z-index: 99; width: 160px; height: 120px; box-shadow: 0px 0px 16px 0px r ...

The Autocomplete feature in Material UI React includes both a "Select All" and a "Select

How can I add Select All and Select None buttons to an Autocomplete component in Material UI React? The goal is for all the options to be checked when Select All is clicked, and for all options to be unchecked when Select None is clicked. <Autocomple ...

The page component constantly refreshes when attempting to create a dynamic layout

After implementing an app that utilizes react-router and Semantic UI React, a portion of the code can be viewed in this gist. The goal is to emulate this method (using Responsive component) to create a responsive layout for mobile and non-mobile devices. ...

I am having difficulty altering the state when submitting an input through a form

Having an issue with my simple form implementation. I have a function addStakes that should trigger when I submit the input, but it's not working properly. The console log doesn't show anything and I'm confused as to why. Can anyone help me ...

Positioning elements in CSS using percentages allows for flexible and responsive

I am new to web design and I am trying to create a webpage similar to the one shown in this image. However, I want to set the height and width of the divs using percentage values instead of pixels. Whenever I attempt this, the boxes end up overlapping or ...

I'm looking for a tool or software that can automatically generate Unit test files for ReactJs

Is there a tool or software available that can automatically generate unit test cases for ReactJs applications? I am looking to find an automated tool that can create unit test cases and identify potential test scenarios - is there such a tool out there ...

How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this: <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="next ...

CSS - Resizing Images

I am experiencing an issue with the width of an image on my website. I want it to span 100% of the browser frame, but it is currently limited to only 1000px wide. Please take a look at: The image in question is located at the top of the page. Is there a ...