Here’s how to Jazz up your country data by adding an image of a flag
This example uses a cell renderer to add an image component to cells in AG Grid. If you have checked out the docs and all that JavaScript looks intimidating, here’s a simple one to get you started. All you need to do is put the JavaScrpt bit in a .js file in the assets folder, everything else can be done in Python.
- Add a column called
country_code
with the standard ISO-3166 country code (It doesn’t even need to be displayed in the grid ) - Add
"cellRenderer": "FlagsCellRenderer"
to the column where you want you want the flag displayed
That’s it!
The cell renderer uses the country code to render the flags from this free site:
"""
Add country flag with a cell renderer
"""
import dash_ag_grid as dag
from dash import Dash, html, dcc
import pandas as pd
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)
COUNTRY_CODES = {
"Ireland": "ie",
"Luxembourg": "lu",
"Belgium": "be",
"Spain": "es",
"France": "fr",
"Germany": "de",
"Sweden": "se",
"Italy": "it",
"Greece": "gr",
"Iceland": "is",
"Portugal": "pt",
"Malta": "mt",
"Norway": "no",
"Brazil": "br",
"Argentina": "ar",
"Colombia": "co",
"Peru": "pe",
"Venezuela": "ve",
"Uruguay": "uy",
}
df = df[df.country.isin(COUNTRY_CODES)]
df["country_code"] = df.country.apply(lambda x: COUNTRY_CODES[x])
app = Dash(__name__)
columnDefs = [
{"field": "country", "cellRenderer": "FlagsCellRenderer"},
{"field": "year"},
{"field": "athlete"},
{"field": "age"},
{"field": "date"},
{"field": "sport"},
{"field": "total"},
]
app.layout = html.Div(
[
dcc.Markdown(
"Example of adding flags to the Country column with a cell renderer"
),
dag.AgGrid(
columnDefs=columnDefs,
rowData=df.to_dict("records"),
columnSize="sizeToFit",
defaultColDef={
"resizable": True,
"sortable": True,
"filter": True,
"minWidth": 100,
},
),
],
style={"margin": 20},
)
if __name__ == "__main__":
app.run_server(debug=True)
"""
Put the following in the dashAgGridComponentFunctions.js file in the assets folder
-----------
var dagcomponentfuncs = window.dashAgGridComponentFunctions = window.dashAgGridComponentFunctions || {};
dagcomponentfuncs.FlagsCellRenderer = function (props) {
// for more info see https://flagpedia.net/
const url = `https://flagcdn.com/h20/${props.data.country_code}.png`;
return React.createElement('span', {}, [
React.createElement(
'img',
{
style: {height: '10px'},
src: url
},
),
React.createElement(
'span',
{
style: {paddingLeft: '4px'},
},
props.value
),
]);
};
"""