How to break lines in Dash AG Grid

I’m trying to join data from two dataframe then show joined dataframe by Dash AG Grid and I have below problem that needs your suggestions:

import dash_ag_grid as dag
from dash import Dash, html, dcc
import pandas as pd
import numpy as np

df = pd.DataFrame({'Definition': ['Loan', 'Deposit'], 
                   '20231015': [28, 17],
                   '20231016': [5, 6],
                   '20231017': [10, 13],
                   'Notes':['','']})
df2 = pd.DataFrame({'BR_CD': ['Hanoi', 'Hochiminh'], 
                   'CUS_NM': ['A', 'B'],
                   'AMT': ['2', '3']})
df2['Conclusion'] = "[" + df2['BR_CD'] + "]" + ' ' + df2['CUS_NM'] + ' ' + df2['AMT'] 
x = "[" + df2['BR_CD'] + "]" + ' ' + df2['CUS_NM'] + ' ' + df2['AMT']

df['Notes'].iloc[1] = '\n'.join(x)

app = Dash(__name__)

app.layout = html.Div([
    dag.AgGrid(
            columnDefs=[{'field':x, 'value':x} for x in df.columns],
            rowData=df.to_dict('records'),
            columnSize="sizeToFit",
            defaultColDef={"editable": True},
        )
])

if __name__ == '__main__':
    app.run_server(debug=False)

I want [Hochiminh] B 3 will be shown under [Hanoi] A 2. How can I achieve that.
Screenshot 2023-10-17 174836

Thank you.

Hello @hoatran,

I use markdown to create line breaks. It also allows for some formatted notes. :grin:

2 Likes

HI @jinnyzor. Sorry for late response.

Can you suggest a little more clearly? Should I convert that Notes Column to markdown?

Correct, you can use the cellRenderer of markdown and then line breaks are space space enter.

Hi @jinnyzor. Thank for your suggestion.
I think my problem was solved by using "cellStyle":{'wordBreak':'normal', 'whiteSpace':'pre'}

import dash_ag_grid as dag
from dash import Dash, html, dcc
import pandas as pd
import numpy as np

df = pd.DataFrame({'Definition': ['Loan', 'Deposit'], 
                   '20231015': [28, 17],
                   '20231016': [5, 6],
                   '20231017': [10, 13],
                   'Notes':['','']})
df2 = pd.DataFrame({'BR_CD': ['Hanoi', 'Hochiminh'], 
                   'CUS_NM': ['A', 'B'],
                   'AMT': ['2', '3']})
df2['Conclusion'] = "[" + df2['BR_CD'] + "]" + ' ' + df2['CUS_NM'] + ' ' + df2['AMT'] 
x = "[" + df2['BR_CD'] + "]" + ' ' + df2['CUS_NM'] + ' ' + df2['AMT']

df['Notes'].iloc[1] = '\n'.join(x)

app = Dash(__name__)

app.layout = html.Div([
    dag.AgGrid(
            columnDefs=[{'field':'Description'}, 
                       {'field':'20231015'}, 
                       {'field':'20231016'},
                       {'field':'20231017'},
                       {'field':'Notes', "wrapText":True, "autoHeight":True, "cellStyle":{'wordBreak':'normal', 'whiteSpace':'pre'}}],
            rowData=df.to_dict('records'),
            defaultColDef={"editable": True},
        )
])

if __name__ == '__main__':
    app.run_server(debug=False)

You can use that, but if you want more control over the break, you can use markdown, otherwise it just wraps when you lose space.

Id also recommend adjusting the lineHeight. That way you get a smaller line gap.

1 Like

Hi @jinnyzor, by the way I have another question that I want to align value vertically centered so I used "cellStyle":{'display':'flex', 'align-items':'center', 'justify-content':'right'}. It worked well with cell without styleConditions. But with cell with styleConditions it unchanged.

import dash_ag_grid as dag
from dash import Dash, html, dcc
import pandas as pd
import numpy as np

df = pd.DataFrame({'Definition': ['Loan', 'Deposit'], 
                   '20231015': [28, 17],
                   '20231016': [5, 6],
                   '20231017': [10, 13],
                   'Notes':['','']})
df2 = pd.DataFrame({'BR_CD': ['Hanoi', 'Hochiminh'], 
                   'CUS_NM': ['A', 'B'],
                   'AMT': ['2', '3']})
df2['Conclusion'] = "[" + df2['BR_CD'] + "]" + ' ' + df2['CUS_NM'] + ' ' + df2['AMT'] 
x = "[" + df2['BR_CD'] + "]" + ' ' + df2['CUS_NM'] + ' ' + df2['AMT']

df['Notes'].iloc[1] = '\n'.join(x)

app = Dash(__name__)

app.layout = html.Div([
    dag.AgGrid(
            columnDefs=[{'field':'Definition'}, 
                       {'field':'20231015',
                        "cellStyle":{'display':'flex', 'align-items':'center', 'justify-content':'right'}}, 
                       {'field':'20231016',
                        "cellStyle":{'display':'flex', 'align-items':'center', 'justify-content':'right'}},
                       {'field':'20231017',
                        "cellStyle":{
                           'styleConditions':
                           [{"condition":'params.value > 0', 
                             'style':{'color':'red'}}],
                        'display':'flex', 'align-items':'center', 'justify-content':'right'}},
                        {'field':'Notes', "wrapText":True, "autoHeight":True, 
                         "cellStyle":{'wordBreak':'normal', 
                                      'whiteSpace':'pre'}}],
            rowData=df.to_dict('records'),
            defaultColDef={"editable": True},
        )
])

if __name__ == '__main__':
    app.run_server(debug=False)

What did I wrong here? Thank you.

Hmm, it would look like that should work, but I believe that the conditional style is the only thing that is being returned.

I’ll have to look at the code to see if there is a way to return the rest of the dictionary when a conditional style is made.

Can you make a GitHub issue?

1 Like

I have never made it before, could you tell me where I need to access?

Sure, here:

Now, with this said, until this is fixed to allow stacking, your workaround would be to place those other styling into the conditional response.

Basically just add your justifyContent to your response when the red styling is applied.

1 Like

I’ve made issue here: cellStyle just work for one condition · Issue #250 · plotly/dash-ag-grid · GitHub

I tried to add justifyContent to style but it seems not work too.

{'field':'20231017',
                        "cellStyle":{
                           'styleConditions':
                           [{"condition":'params.value > 0', 
                             'style':{'color':'red','display':'flex', 'align-items':'center', 'justify-content':'right'}}],
                        'display':'flex', 'align-items':'center', 'justify-content':'right'}},

Try this.

1 Like

Thank you, it worked. It’s quite funny that I tried the same thing before but it failed haha :grinning:

1 Like

Hi @hoatran

Note that the solution posted above will not work as expected if one of the conditions is not met. For example try it with params.value > 10.

You also need to include the defaultStyle:

{
    "field": "20231017",
    "cellStyle": {
        "styleConditions": [
            {
                "condition": "params.value > 10",
                "style": {
                    "color": "red",
                    "display": "flex",
                    "align-items": "center",
                    "justify-content": "right",
                },
            }
        ],
        # Default style if no rules apply
        "defaultStyle": {
            "display": "flex",
            "align-items": "center",
            "justify-content": "right",
        },
    },
}

You could make it less verbose by using variables:

centered = {"display": "flex", "align-items": "center", "justify-content": "right"}

{
    "field": "20231017",
    "cellStyle": {
        "styleConditions": [
            {
                "condition": "params.value > 10",
                "style": {**{"color": "red", **centered}},
            }
        ],
        # Default style if no rules apply
        "defaultStyle": centered,
    },
},


3 Likes

HI @AnnMarieW, thank for your response. I will note that.