Ag Grid, change column colour based on other column's value

Hi everybody, I am trying to make A green when B is “yes”. In other words, elem1 and alem 3 should be displayed with green background in Ag-Grid.

| Header A | Header B |
| elem1 | yes |
| elem2 | no |
| elem3 | yes |

This code is not working, somebody could tell me why? thanks in advance

   cellsytle_jscode = JsCode("""
    function(params) {
        if (df['Header B'].value == 'yes') {
            return {
                'color': 'white',
                'backgroundColor': 'green'
            }
        } else {
            return {
                'color': 'black',
                'backgroundColor': 'red'
            }
        }
    };
    """) 
    
    gb.configure_column("Header A", cellStyle=cellsytle_jscode)

You can access the values of other columns in the same row using params.data.{row of interest}.

So in your example it would be somthing like:

   cellsytle_jscode = JsCode("""
    function(params) {
        if (params.data.Header B == 'yes') {
            return {
                'color': 'white',
                'backgroundColor': 'green'
            }
        } else {
            return {
                'color': 'black',
                'backgroundColor': 'red'
            }
        }
    };
    """) 
    
    gb.configure_column("Header A", cellStyle=cellsytle_jscode)

You’ll likely need it to be “Header_B” instead of “Header B”. A quick way of looking at what you can access from params would be to stick a console.log(params) in before the if block.

Hope that works!

1 Like

One question is, can this css style be based on the updated dataframe value? I found that if I use this, and update one of the columns by allowing editing in the dataframe, the style doesn’t update with the color. I wonder if there’s any solution there.

Hello @Ben_Morris, in my case I want the cell to activate the function to edit the value, if it meets the condition otherwise it can not be edited, I help me thanks.