React
Using ag-Grid with React: Styling

Cell Styling

Outline

Sometimes we want to style individual cells instead of entire rows. We can do this inside of the definition of the columns that will hold the cells we want to style. Like row styling, we can do this with styles or classes, either with strings or callbacks. We can also define cell class rules just like we did with rows.

The first way to style a cell is to add a cellStyle property to a column definition. In the video we do this in the amount column definition. The value of this property is an object with CSS styles:

// App.js state
// amount column definition
cellStyle: {color: 'white', 'background-color': 'darkred'}

To add styles conditionally, we can just change cellStyle to a callback function:

// App.js state
// amount column definition
cellStyle: (params) => {
  if (params.value <= 100) {
      return {background: 'darkred', color: 'white'};
  }
}

As with rows, we can use classes to style cells with either a string (or an array of classes as strings) or a function with the cellClass property. Here's that property with a class name as a string:

cellClass: "ag-red"

The cellClass property can also take an array:

cellClass: ['ag-red', 'test']

As with rowClass, cellClass can also be a function:

cellClass: (params) => {
  if (params.value <= 100) {
     return 'ag-red';
   }
 }

The cellStyle and cellClass properties are really useful, but they have the same issue that we've encountered before where updating the amounts leads to more and more cells getting that ag-red class added without being removed. Luckily, Cell Class Rules take care of that. These rules work the same way as Row Class Rules, except that we'll use params.value instead of params.data.amount since we're already in the column definition:

cellClassRules: {
  "ag-red": (params) => {
    return params.value <= 100;
  },
    "ag-amber": (params) => {
    return params.value > 100 && params.value <= 200;
  },
    "ag-green": (params) => {
     return params.value > 700;
   },  
}

Cell Class Rules also have a shorthand syntax like Row Class Rules. We can simplify the above rules to the following:

cellClassRules: {
   "ag-red": "x <= 100",
   "ag-amber": "x > 100 && x <= 200",
   "ag-green": "x >= 700",
},

Check out the docs on Cell Class Rules to learn more about this shorthand.

Up next: let's add some colors that will appear when we hover over rows and columns.

 

I finished! On to the next chapter