Applying Multiple Conditions to setCellProps in Material-UI

I am facing an issue with a data-table that is not in a class extending the React.Component, unlike some examples I have come across. My goal is to setCellProps based on certain conditions as outlined below:

If utilization is less than or equal to 50, then color should be green and padding should be 5. If utilization is greater than 50, then color should be red and padding should still be 5.

I have not been able to locate any examples of how to handle multiple conditions like this without extending react...

<code>
const rowContents = teams.filter((team) => !!utilizations[team.id])
                          .map((team: Team) => ({
                                team,
                                summary: utilizations[team.id].getSummary(),
                              }))
                              .map(({ team, summary }) => (
                                [team.name,                                          // name
                                 summary.utilization.toLocaleString()])       

const columns = [
    {
      name: "Team",
      options: {
       filter: true,
       setCellProps: () => ({ style: { padding: 5 }}),
       setCellHeaderProps: () => ({ style: { padding: 5 }}),


     }
    },
    {
      name: "Utilization",
      options: {
       filter: true,
       setCellProps: () => ({ style: { padding: 5 }}),
       setCellHeaderProps: () => ({ style: { padding: 5 }}),

     }
    }

return (
    <MUIDataTable
    title={'Teams'}
    columns={columns}
    data={rowContents}
    options={
              {"draggableColumns":{"enabled":true},
               "pagination":false,
               "selectableRows":"none"}
            }
    />     
  );

Answer №1

After some trial and error, I finally figured out how to implement conditional styling in datatables. Sharing my solution here for anyone else who may be facing the same challenge:

Check out this code snippet that demonstrates how to apply conditional styling based on a certain condition...

{
      name: "Utilization",
      options: {
       filter: true,
       setCellProps: (cellValue:string, dataIndex:integer, rowIndex:integer) => {
        return {
          style: Number(cellValue) > 50  ? {color: "red", padding: 5} : {color: "black", padding: 5}
        };},
       setCellHeaderProps: () => ({ style: { padding: 5 }}),


     }

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

Utilize Dinero.js to implement currency formatting for input fields in React applications

I am currently working on a form in React that requires certain input fields to be formatted as money currency. These inputs should be prefixed with the dollar sign ($), include commas for thousands separation, and have exactly two decimal points. During ...

Angular 5 ngx-modialog issue TS2307: Module 'ngx-modialog/plugins/vex' not located

After installing module ngx-modialog using the Angular 5 CLI like this: npm install --save ngx-modialog I then added it to my app.module.ts: import { VexModalModule } from "ngx-modialog/plugins/vex"; import { ModalModule } from "ngx-modialog"; @NgModul ...

Navigating Mixins in Ember CLI Typescript

I'm curious about the best approach for handling mixins in a typed Ember application. While removing mixins from the application is ideal, many addons do not yet support TypeScript. So, how can we effectively utilize Ember Simple Auth's applicati ...

Challenges in handling asynchronous data within static JSON objects in Angular2

I have a service set up with some static objects that are being utilized in my UI. fetchRulesVariables() fetchRuleVariables() { let variables = [ { name: 'Credit Funding Type', id: 1, multiple: ...

What causes React Hook Form to return undefined upon submission?

I am currently working on a project using TypeScript. In this project, I have a form that should output 4 values after submitting the form. However, only the input field linked to the controller is sending a value, while the others are returning undefined: ...

Configuring the React Typescript router to support username-based URLs should be done in a way that does not cause conflicts with other routes

I am looking to display a user's profile on a URL format such as www.domain.com/<userName> and load the component ShowProfile. I want to ensure that terms is not mistaken for a username, so if I visit www.domain.com/terms, I do not want to load ...

Tips for removing data from documents that include automatically generated IDs

In my Angular project, I am utilizing google-cloud-firestore as the database. To import Firestore, I used the code import { AngularFirestore } from '@angular/fire/firestore';. The following function is used to add data to the database: changeLev ...

What is the correct data type for the vuex store that is passed to the vuex plugin when it is being initialized?

Here is how the store initialization process is currently being implemented: /* Logic */ import Vue from 'vue' import Vuex, { StoreOptions } from 'vuex' Vue.use(Vuex) const DataManager = new UserDataManager() type RootStateType = { ...

Enable lazy loading to retrieve the current routed module

I'm currently working on a way to exclude a component when a specific module is routed in a lazy loading application. For instance, in my AppComponent I have a router-outlet and a component above it: <div> <my-component></my-compo ...

Watchable: Yield the outcome of a Promise as long as watching continues

I am looking to create a function in Angular and TypeScript that will return an Observable for subscription. This Observable should emit the result of a Promise every three seconds. Currently, I have a function that returns a Promise, but I need it to ret ...

Is there a way for me to verify that the key of one object is a subset of the keys of another object?

export const masterKeysObject = { MAIN: 'main', REDIRECT: 'redirect', DASHBOARD: 'dashboard', USER_ID_PARAM: ':userId', CREATE_NEW: 'create_new' } as const; type MasterKeys = keyof type ...

Interact and share information between Material UI components in React

Utilizing Material UI's nested/select ItemList component, I have created a dynamic dropdown menu that generates multiple items based on the content of the header. The mapping function in the code helps to render these items. In another file situated o ...

The Material UI selection menu is presented in a horizontal orientation instead of the typical vertical

I'm encountering an issue with a Material-UI Box that contains 2 components: a TextField acting as a Select with MenuItems for a menu, and a button beneath the TextField to delete selected content in the select. The problem arises when I add the butto ...

Centering items in Material UI Grid

I'm currently grappling with understanding Material UI's grid system and implementing it in React.js, and I find it a bit perplexing. My goal is to center the spinner loader and text irrespective of viewport size. While I can manage to place the ...

Is there a way for me to view the output of my TypeScript code in an HTML document?

This is my HTML *all the code has been modified <div class="testCenter"> <h1>{{changed()}}</h1> </div> This is my .ts code I am unsure about the functionality of the changed() function import { Component, OnInit } f ...

Utilize the text box feature for manipulating the data field in Angular4

Within my grid view, there exists a column labeled remark. This specific field contains various values, one of which is absence. My objective is to modify the remark value exclusively when it is equal to absence, followed by clicking the corresponding icon ...

Strange rendering issues when using the react material-ui dialog

Exploring the Project Recently, I developed a front-end project focusing on a delivery service using React and Material UI. One interesting feature I added was a Dialog window that pops up when users click on an item, allowing them to customize it. Here i ...

Display the date string in Material-UI TableCell格式

I have a TableCell component in Material-UI that displays dates in the format 2019-03-25T19:09:21Z: <TableCell align="left">{item.created_at}</TableCell> I want to change this to a more user-friendly format showing only the date as either 25/ ...

Increase the timestamp in Typescript by one hour

Is there a way to extend a timestamp by 1 hour? For instance, 1574620200000 (Including Microseconds) This is my date in timestamp format. How can I add a value to the timestamp to increase the time by an additional hour? ...

Using a vector image as the backdrop for a Floating Action Button

I am struggling to set a vector or mipmap as the background for a Floating Action Button. Can anyone help me figure out what's going wrong? xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com ...