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.
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.
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' } });
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.
onClick
works, but sometimes you need an actual <a>
tag for various reasons:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With