javascriptreactjsiconsag-grid

How can I add icon to react ag-grid rows?


I use react ag-grid library and I tried cellRenderer function, but it doesn't work.

columnDefinitionWaterUsage: [
  { headerName: "", cellRenderer: countCellIndex, width: 45, minWidth: 40, editable: false, },
  { headerName: "Yıl", field: "Year", width: 50, minWidth: 50, maxWidth: 100, suppressSizeToFit: false, sortable: true },
  { headerName: "Dönem", field: "TermSequence", width: 75, minWidth: 50, maxWidth: 100, suppressSizeToFit: false },
  { headerName: "İlk Endeks", field: "FirstIndex", width: 90, minWidth: 50, maxWidth: 150, suppressSizeToFit: false },
  { headerName: "Son Endeks", field: "LastIndex", width: 95, minWidth: 50, maxWidth: 150, suppressSizeToFit: false },
  { headerName: "Tüketim", field: "UsageAmount", width: 75, minWidth: 50, maxWidth: 100, suppressSizeToFit: false },
  { headerName: "Tutar", field: "TotalAmount", width: 60, minWidth: 50, maxWidth: 100, suppressSizeToFit: false },
  { headerName: "Son Ödeme Tarihi", cellRenderer: (data) => { return ChangeDateFormatRowdata(data.data.LastPaymentDate) }, width: 135, minWidth: 50, maxWidth: 200, suppressSizeToFit: false },
  { headerName: "Okuma Tarihi", cellRenderer: (data) => { return ChangeDateFormatRowdata(data.data.ProcessDate) }, width: 110, minWidth: 50, maxWidth: 200, suppressSizeToFit: false },
  { headerName: "Tahakkuk", cellRenderer: actionCellRenderer, width: 85, minWidth: 50, maxWidth: 200, suppressSizeToFit: false },
  { headerName: "Tahsilat", cellRenderer: actionCellRenderer, width: 85, minWidth: 50, maxWidth: 200, suppressSizeToFit: false },
]

My function is:

function actionCellRenderer(params) {
  return '<span><i class="bi-react-icons"><BiCoinStack/></i></span>'       
}

How can I add icons in ag grid rows ?


Solution

  • You should create a normal react component instead of using template string. You can see the props structure of the custom renderer here.

    function IconComponent(props) {
      return <YourIcon />
    }
    

    Then register in AgGridReact:

    <AgGridReact
      frameworkComponents={{
        iconComponent: IconComponent
      }}
    

    Finally, tell your column to use your custom icon renderer:

    const columnDefs: ColDef[] = [
      {
        headerName: "Country",
        field: "country",
        width: 120,
        cellRenderer: "iconComponent"
      }
      ...
    ]
    

    Live Demo

    Codesandbox Demo

    Reference