material-table icon indicating copy to clipboard operation
material-table copied to clipboard

Make the entire row a link

Open deadghost opened this issue 7 years ago • 16 comments

material-table provides a lot of functionality I need out of the box: search, sort, export, etc. In my case I'm not using the editing functionality and would like the row to link to a page that allows editing the entry. My first thought was the override the Row component and wrap MTableBodyRow in a; however, this is invalid HTML. My second thought was to use the onRowClick prop but it wouldn't display the link url on hover and generally seems smelly. My current approach is the override each cell's rendering with a mui Link such that <a> appears inside <td>. It's ok but not ideal.

Do you have any thoughts on doing this in a clean way using material-table?

deadghost avatar Jul 11 '19 15:07 deadghost

I was trying to add a link to elements in a column and onclick route to a new page. Did you try anything of this sort? Any suggestions?

meldsz avatar Jul 12 '19 13:07 meldsz

however, this is invalid HTML

Not if you change the other components and use css to create the table using display

eddiemonge avatar Jul 12 '19 18:07 eddiemonge

Looks like your answer may be here:

https://github.com/mbrn/material-table/issues/824

The docs point us in the right direction: https://material-table.com/#/docs/features/custom-column-rendering

...and here's "render" property on a column I just used as a proof of concept. It's working as expected... render: rowData => <a href={'/path/view_note/' + rowData.note_id}>Test Link</a>

michaelpward avatar Jul 15 '19 03:07 michaelpward

@michaelpward yeah that's essentially the approach I was previously using. It doesn't make the whole row a link but makes a link inside each <td>. It essentially works but it kind of smells.

deadghost avatar Jul 15 '19 18:07 deadghost

Also curious if there's a better solution, but the custom wrapping works for now

Any update on this? Did anyone find a solution? Thanks in advance.

tylercaceres avatar Nov 26 '19 23:11 tylercaceres

Since the component uses regular HTML table elements for rendering tables, such as <table><tbody><tr><td> there's technically no chance to make the entire row a link. See also this StackOverflow answer. The only option left is to render a link inside each <td> cell.

In order to apply the same link to each cell you can use the following pattern to avoid rewriting the same render function for each column. The following approach involves the lookup dictionary in case you use that feature:

<MaterialTable
  columns={[
    {
      title: "Column 1,
      field: "column1",
    },
    {
      title: "Column 2",
      field: "column2",
      lookup: {
        '1': 'one',
        '2': 'two',
        '3': 'three',
      },
    },
  ].map(c => (
    {render: row => <Link to={row.url}>{c.lookup ? c.lookup[row[c.field]] : row[c.field]}</Link>, ...c}
  ))}
  ...

larsblumberg avatar Dec 18 '19 08:12 larsblumberg

** Edit 1 - remove a stupid mistake and show the final answer ** ** Edit 2 - add SO link to do an external redirect **

As @larsblumberg points out, you can't make the entire row an <a> in pure html. But there's no reason you couldn't use javascript.

Internal links

For those using react-router, it is possible to push() to history in the onRowClick() callback, thereby providing an internal redirect on row click.

Here's the code:

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { push } from 'connected-react-router'
import MaterialTable from 'material-table'


class ResourceTable extends Component {
  constructor(props) {
    super(props)
    this.onRowClick = this.onRowClick.bind(this)
  }

  onRowClick(event, rowData) {
      this.props.onViewItem(this.props.endpoint, rowData.id)
  }

  render() {
    const {
      endpoint,
      ...rest
    } = this.props

    return (
      <MaterialTable
        onRowClick={this.onRowClick}
        {...rest}
      />
    )
  }
}

const mapDispatchToProps = dispatch => ({
  onViewItem: (endpoint, id) => {
    dispatch(push(`${endpoint}/${id}`))
  },
})

export default connect(null, mapDispatchToProps)(ResourceTable)

This works like a charm (and would be even more elegant with react hooks)!

External link

You can link externally with javascript using the information in this SO post... simply replace the window.location in the onRowClick callback.

thclark avatar Dec 25 '19 18:12 thclark

For anyone looking at this, I was very happy when I found the solution here: https://github.com/mbrn/material-table/issues/547

yujinwunz avatar May 13 '20 12:05 yujinwunz

if you are willing to use React Router (v5), you can push it to history which will render the page for you automatically. You have top tap into onRowClick functionality for Material-Table.

here is a sample

import React from "react";
import MaterialTable from "material-table";
//others ignored for brevity
import { useHistory } from "react-router-dom";

export default function Demo() 
{
  let history = useHistory();
  return 
    (
      <div> 
      <MaterialTable 
        columns=[//ignored for brevity]
        data=[//ignored for brevity]
        onRowClick={(event, rowData) => {
          //for a static path with no params
          history.push("/demopath");
          //for dynamic path with id coming from data, feel free to edit history.push above
        }}
       />
      </div>
     )
 }

and wherever you are using your React Router Switch, add your <Route path="demopath" component={myDemoPathComponent} /> to the switch.

if you would like to ignore certain parts of the components upon forwarding to myDemoPathComponents, see React Router how to hide components from path.

orhanhub avatar May 15 '20 03:05 orhanhub

What's wrong with onRowClick? You can easily override the row component..

To accomplish this, override the row component by using the default row component (MTableBodyRow) wrapped in a div with a title attribute.

Similar to the example below, but using the row component mentioned above and a title attribute instead of style..

You should be able to integrate logic which determines the rendered title.

Taken from the docs:

import MaterialTable, { MTableToolbar } from 'material-table';

<MaterialTable
    // other props
    components={{
        /**
         * INSTEAD OF `Toolbar:` this would be `Row:`
         */
        Toolbar: props => (
            <div style={{ backgroundColor: '#e8eaf5' }}>
                <MTableToolbar {...props} />
            </div>
        )
    }}
/>

matthewoestreich avatar May 15 '20 05:05 matthewoestreich

thanks for the response @oze4, wrapping MTableBodyRow in a div causes validateDOMNesting error on the console and the table formatting is ignored. To fix it you can use MTableBodyRow without wrapping in a div.

orhanhub avatar May 17 '20 16:05 orhanhub

@orhanhub nice! Glad it works.

matthewoestreich avatar May 17 '20 16:05 matthewoestreich

This issue looks to be resolved. Please open if you feel it was closed in error.

matthewoestreich avatar May 31 '20 17:05 matthewoestreich

I must say that I'm totally lost for how to achieve this behavior. I need to convert a row into <a> tag. My previous solution was styling the row with a display:table-row. How can I modify a MTableBodyRow to replicate same behavior?

alexander-r-jaimy avatar Aug 25 '20 15:08 alexander-r-jaimy

thanks for the response @oze4, wrapping MTableBodyRow in a div causes validateDOMNesting error on the console and the table formatting is ignored. To fix it you can use MTableBodyRow without wrapping in a div.

"use MTableBodyRow without wrapping in a div" ? Any sample code please. I would think I have to wrap it in something. Thank you

gideonaina avatar Jun 02 '21 17:06 gideonaina