Reputation: 301
I have a simple table, and I need to Link to another component, when a row is clicked. Right now I have one column of clickable data in the table. Is it possible to do it in a simple way? I have tried different ways to solve this task, but seems like most of the answers are already outdated...
This is what I have:
<tbody>
{this.state.users.map((user, id) => {
return (
<tr key={ user.id }>
<td><Link to={`/user/${user.id}`}>{ user.id }</Link></td>
<td>{ user.first_name }</td>
<td>{ user.last_name }</td>
<td>{ user.email }</td>
<td>{ user.gender }</td>
<td>{ user.ip_address }</td>
<td>{ this.state.total_clicks[user.id] }</td>
<td>{ this.state.total_page_views[user.id] }</td>
</tr>
)
})}
</tbody>
This is what I want:
<tbody>
{this.state.users.map((user, id) => {
return (
<Link to={`/user/${user.id}`}>
<tr key={ user.id }>
<td>{ user.id }</td>
<td>{ user.first_name }</td>
<td>{ user.last_name }</td>
<td>{ user.email }</td>
<td>{ user.gender }</td>
<td>{ user.ip_address }</td>
<td>{ this.state.total_clicks[user.id] }</td>
<td>{ this.state.total_page_views[user.id] }</td>
</tr>
</Link>
)
})}
</tbody>
Upvotes: 0
Views: 941
Reputation: 2822
Yes,
but to do this, you need to setup a onClick
handler on the tr
component. Which means the page change can be done only programmatically and not via a component like Link.
I assume you use react-router-dom
. To do this, you need to put the withRouter
HOC on your table. Then you have access to the history
prop which lets you do a history.push('/new-url')
.
Gathering all things together it gives this :
const MyComponent = ({history}) => {
return (
<tbody>
{this.state.users.map((user, id) => (
<tr key={ user.id } onClick={() => history.push(`/user/${user.id}`)}>
/* stuff */
</tr>
)}
</tbody>
)
}
export default withRouter(MyComponent)
Upvotes: 1