Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router: Using <Link> as clickable data table row

I'm new to using ReactJS and react-router. I want a clickable table row and something like the following setup:

<Link to=“#”> <tr>     <td>{this.props.whatever1}</td>     <td>{this.props.whatever2}</td>     <td>{this.props.whatever3}</td> </tr> </Link> 

but I know you can't put <a> tags between the <tbody> and <tr> tags. How else can I accomplish this?

PS: I prefer not to use jQuery if possible.

like image 615
jfrye Avatar asked Feb 22 '16 22:02

jfrye


People also ask

Can you make a table row a Link?

So we can easily make the table row clickable as a link using bootstrap. You can include Javascript to do so or it can be done without using Javascript by adding anchor to each <td> element.

How do you pass data with router navigate in react?

To pass data when navigating programmatically with React Router, we can call navigate with an object. Then we can use the useLocation hook to return the object's data. const navigate = useNavigate(); navigate('/other-page', { state: { id: 7, color: 'green' } });

How do I add a hyperlink in dom react router?

To add the link in the menu, use the <NavLink /> component by react-router-dom . The NavLink component provides a declarative way to navigate around the application. It is similar to the Link component, except it can apply an active style to the link if it is active.


1 Answers

onClick works, but sometimes you need an actual <a> tag for various reasons:

  • Accessibility
  • Progressive enhancement (if script is throwing an error, links still work)
  • Ability to open a link in new tab
  • Ability to copy the link

Here's an example of a Td component that accepts to prop:

import React from 'react'; import { Link } from 'react-router-dom';  export default function Td({ children, to }) {   // Conditionally wrapping content into a link   const ContentTag = to ? Link : 'div';    return (     <td>       <ContentTag to={to}>{children}</ContentTag>     </td>   ); } 

Then use the component like this:

const users = this.props.users.map((user) =>       <tr key={user.id}>         <Td to={`/users/${user.id}/edit`}>{user.name}</Td>         <Td to={`/users/${user.id}/edit`}>{user.email}</Td>         <Td to={`/users/${user.id}/edit`}>{user.username}</Td>       </tr>     ); 

Yes, you'll have to pass to prop multiple times, but at the same you have more control over the clickable areas and you may have other interactive elements in the table, like checkboxes.

like image 184
Igor Barbashin Avatar answered Oct 09 '22 08:10

Igor Barbashin