Home > front end >  Can't add links to table rows in React App
Can't add links to table rows in React App

Time:01-27

I wrote React function to render table. That's how the table look.

As a parameter it takes JSON:

{
    "id": 1,
    "firstName": "Richard",
    "lastName": "Morrison",
    "numberOfAccidents": 1
},
{
    "id": 3,
    "firstName": "Gregory",
    "lastName": "House",
    "numberOfAccidents": 5
} 

Part of Table function which render rows:

<tbody {...getTableBodyProps()}>
{rows.map((row) => {
    prepareRow(row)
    return (
        <tr {...row.getRowProps()}>
            {row.cells.map(cell => {
                return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
            })}
        </tr>
    )
})}
</tbody>

I want to add link to '/patient/$id' to each row. I tried to write smth like:

return <td to={‘/patient/’   cell.getCellProps().data.id} {...cell.getCellProps()}>{cell.render('Cell')}</td>

and

const handlerRowClick = (row) => { history.push(`/patient/${row.original.id}`); }
...
return <td onClick={() => handlerRowClick(row)} {...cell.getCellProps()}>{cell.render('Cell')}</td> 

but it doesn't work. I would like to ask for advice or links wich can help me to solve my problem.

Thanks!

CodePudding user response:

You should use NavLink comopenent in react-router-dom.

import { NavLink } from "react-router-dom";

<td {...cell.getCellProps()}>
    <NavLink to={`/patient/`   cell.getCellProps().data.id}>
        {cell.render("Cell")}
    </NavLink>
</td>

CodePudding user response:

If you use react-router-dom, you can redirect users on several ways.

  1. Using <Link> component (docs),
  2. Using function useHistory (docs),
  3. Using <NavLink> component (docs),
  4. Using <Redirect> component (dosc)
  •  Tags:  
  • Related