1

I am working Material-UI tables, such as the following basic table here but I have added an id column at the beginning.

Assuming I have this basic table example at the route localhost:3000/basic-table within my React app, how can I take the below code and make the <tableCell>{row.id}</tableCell> into a <a href link> which will allow the user to click on this {row.id} column and then present the user with a new screen, where I can take this id and show more data about it?

I will also need a means of returning back to the main page report, i.e. parent page.

What I am trying to achieve is basically from the main parent report, a user can click on a row id, which would then present the user with a detailed report based on that id, i.e. like a drill-down report.

From the doco, I can't find any examples where I can achieve this as unsure how to add a column link.

Can anyone help with this or point me to an example.

      {rows.map((row) => (
        <TableRow key={row.id}>
          <TableCell component="th" scope="row">
            {row.id}
          </TableCell>
          <TableCell align="right">{row.name}</TableCell>
          <TableCell align="right">{row.calories}</TableCell>
          <TableCell align="right">{row.fat}</TableCell>
          <TableCell align="right">{row.carbs}</TableCell>
          <TableCell align="right">{row.protein}</TableCell>
        </TableRow>
      ))}
ArthurJ
  • 777
  • 1
  • 14
  • 39
  • For other people, the below answer is fine but I ended up using the following code {value} to achieve my requirement. This is from https://stackoverflow.com/questions/50691049/how-to-add-link-react-router-per-each-material-ui-tablerow – ArthurJ Jun 19 '21 at 02:36

1 Answers1

1

You can use history API

import { useHistory } from 'react-router-dom';

const YourComponent = () => {
...
const history = useHistory();
return {
    ...
    rows.map((row) => (
        <TableRow key={row.id} onClick={() => history.push(yourLocation)}>
          <TableCell component="th" scope="row">
            {row.id}
          </TableCell>
          <TableCell align="right">{row.name}</TableCell>
          <TableCell align="right">{row.calories}</TableCell>
          <TableCell align="right">{row.fat}</TableCell>
          <TableCell align="right">{row.carbs}</TableCell>
          <TableCell align="right">{row.protein}</TableCell>
        </TableRow>
      ))}
}
Kostya Tresko
  • 754
  • 1
  • 5
  • 24
  • I actually just want a link on the `{row.id}` column alone and when the user clicks on this id column link, how can I pass this id value to say `localhost:3000/basic-table/summary?id=5? With your `push(yourLocation)` - does this need to be a route I need to create in my App.js? – ArthurJ Jun 18 '21 at 10:03
  • You can push any route. `history.push('/basic-table/summary?id=${row.id}')` – Kostya Tresko Jun 18 '21 at 10:47
  • You can use history API anywhere in your code to navigate to desired page – Kostya Tresko Jun 18 '21 at 10:51