I'm fairly new to React. I have a Component named Content, that serves as a container for 2 other components called List and Profile.
class Content extends Component{
<HashRouter>
<Route exact path="/list">
<List *props are entered here*/>
</Route>
<Route exact path="/profile">
<Profile foo = {this.foo} *props are entered here*/>
</Route>
</HashRouter>
}
Inside List, I have a table of users that I mapped out from the state. When I click on the link, function foo gets the user id and passes it on to Profile, the List component will be replaced with the Profile component, displaying the selected user profile
<table>
<thead>
<tr >
<th>User</th>
<th>Link to profile</th>
</tr>
</thead>
<tbody>
{this.state.users.map((user, index) =>
<tr key={index}>
<td>{user.name}</td>
<td><Link to="/profile" onClick={() => this.props.foo(user.id)}</Link></td>
</tr>
)}
</tbody>
</table>
Now clicking on the link inside the <td> obviously works, but I want to make the entire row act like a clickable <Link>
I tried binding an onClick function to <tr> but I don't know how to make it act like a <Link> where it replaces the component to Profile
EDIT: I managed to make it work using withRouter as per Jacob Smit's comment
I included withRouter from react-router-dom
export default withRouter(List)Added an onClick function in
<tr>and a data-value attribute<tr key={index} onClick={this.clickRow} data-value{user.id}>in the clickRow() function
this.props.foo(event.currentTarget.getAttribute("data-value"); this.props.history.push("/profile")
I didn't pass the user.id in clickRow because for some odd reason, it automatically triggers it when the page is loaded so I tried to remove it. Haven't investigated yet but will work this solution for now.
withRouterto pushhistoryonto your component through props. you can then usehistory.push(/* URL HERE */)to make the application route. If you use any function components you can use the hookuseHistoryinstead of thewithRouterHOC. - Jacob Smit