简体   繁体   中英

How to change Header name dynamically in AG-Grid React?

I want to change the header icon dynamically(ie based on the data coming from back end).

I searched through the internet but didn't find much solution and the documentation doesn't had the clear implementation.

So, I thought to share it here.

Sample Code:

export function ColumDefinition(dataFromAPI) {
    return [
        {
            field: 'abc1', 
            resizable: true,
            flex:1,
            headerClass: "xyz1",
            lockPosition: true
        },
        {
            field: 'abc2', 
            width: 140,
            headerClass: "xyz2",
            lockPosition: true
        }
    ] }

Useful Links:

  1. AG-Grid dynamic column header text
  2. https://blog.ag-grid.com/automatic-header-names/#valuegetter-header-names
  3. https://www.ag-grid.com/react-data-grid/value-getters/#header-value-getters

I used headerComponentParams to solve this.

Column Definition :

export function ColumDefinition(dataFromAPI) {
    return [
        {
            field: 'abc1', 
            resizable: true,
            flex:1,
            headerClass: "xyz1",
            lockPosition: true
        },
        {
            field: 'abc2', 
            width: 140,
            headerClass: "xyz2",
            lockPosition: true,
            headerComponentParams: (params) => {
                let icon = dataFromAPI === "X" ? Data1 : Data2;
                return { template: `<div class="abc">HeaderName <img class="abcd" src=${icon}>` }
            },
        }
    ]
}

To pass the API data I used it in below way:

const ModuleGridLoad = (RowData) => {
    setColumDefinitionColDef(ColumDefinition(props.dataFromAPI));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM