Clickable url value in ag-grid with react

后端 未结 2 937
说谎
说谎 2021-01-17 23:47

I\'m currently giving ag-grid a try and trying to build a table where if the user clicks a column value, they are taken to a page containing that entry\'s details.

<

相关标签:
2条回答
  • 2021-01-18 00:21

    You want to use a cellRenderer for that, instead of valueGetter:

    https://www.ag-grid.com/javascript-grid-cell-rendering-components/#gsc.tab=0

    Random example from above documentation:

    // put the value in bold
    colDef.cellRenderer = function(params) {
        return '<b>' + params.value.toUpperCase() + '</b>';
    }
    

    You can return a string (easier) with your link if you don't want to attach any events.

    Otherwise, here's an example of a colDef if you want to attach events to an element:

    {
        headerName: 'ID',
        field: 'id',
        cellRenderer: (params) => {
            var link = document.createElement('a');
            link.href = '#';
            link.innerText = params.value;
            link.addEventListener('click', (e) => {
                e.preventDefault();
                console.log(params.data.id);
            });
            return link;
        }
    }
    
    0 讨论(0)
  • 2021-01-18 00:45

    Since you've already used React, you should use frameworkComponent instead. Somebody mentioned about the overhead of React but because this is a very simple component, I do not think it matters much in this case.

    Anyway, here is the example setup.

    function LinkComponent(props: ICellRendererParams) {
      return (
        <a href={"https://yourwebsite/entity/detail?id=" + props.value}>
          {props.value}
        </a>
      );
    }
    
    ...
    
    // in your render method
    <AgGridReact
      {...}
      columnDefs={[...,{
        headerName: "Detail",
        field: "detail",
        cellRenderer: "LinkComponent"
      }]}
      frameworkComponents={{
        LinkComponent
      }}
    />
    

    Live Example

    0 讨论(0)
提交回复
热议问题