3
votes

Currently working with AG-grid library and react to render data in a table. Here is a simple example of what I'm trying to do:

Soccer Player
player1
player2
player3

In the above column I want to change the color of the column based on the number of goals the player has scored. In AG-Grid I can't find a way to do this. AG-Grid allows you to define Cell Styling Rules, but as far as I can tell the rules are dependent on the value in that cell. In the above example a Player Name cell might be highlighted green if they have scored 10 or fewer goals, blue if they have scored 20 or fewer goals, etc.

Does anyone have any ideas on how to do this, or could recommend another library that might have this functionality?

1

1 Answers

5
votes

The ag-grids document on cell styling says that you can define a cellStyle in the column definition. Either you can define the style object manually or can use a function that will return a object of css styles.

For your case you can use a function to access the row nodes data and compute your styles based on that. In sort you want to do this:

var columnDef = [{
    headerName: "Player Id",
    field: "id"
  },
  {
    headerName: "Player Name",
    field: "playerName",
    cellClass: "playerNameClass",

    // Defining the cell style by using a function

    cellStyle: function(params) {

      /*
      Params give assess to the row node from which we can
      get the node data. So you can get the data for
      another column and style your column based on that.
      */

      var goals = params.node.data.goalsScored;
      console.log({
        "params": params,
        "data": params.data,
        "goals": goals
      });

      // Some Logic to style your components

      if (goals === 0) {
        background = "#B70000"
      } else if (goals === 1 || goals === 2) {
        background = "#FF8400"
      } else if (goals === 3 || goals === 4) {
        background = "#FFF700"
      } else if (goals === 5 || goals === 6) {
        background = "#CEFF00"
      } else if (goals === 7) {
        background = "#05CC00"
      } else {
        background = "#fff"
      }

      // Return the style object

      return {
        background: background
      };
    }
  },
  {
    headerName: "Goals Scored",
    field: "goalsScored"
  }
];

Check out this pen for a detailed example: http://codepen.io/skmSoumya/pen/bqyyQj