1
votes

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

  1. I included withRouter from react-router-dom

    export default withRouter(List)

  2. Added an onClick function in <tr> and a data-value attribute

    <tr key={index} onClick={this.clickRow} data-value{user.id}>

  3. 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.

1
since you are using class components you can use withRouter to push history onto your component through props. you can then use history.push(/* URL HERE */) to make the application route. If you use any function components you can use the hook useHistory instead of the withRouter HOC. - Jacob Smit
This worked! Thank you! - ecfz

1 Answers

2
votes
  1. put an onClick event on

    <tr key={index} onClick={this.handleOnClick(user.id)}>

  2. in handleOnClick, use Redirect to link to another page, also you may need to pass props to Redirect.

handleOnClick = (userid) => {
      return <Redirect
      to={{
        pathname: "/profile",
        foo: userid
        
      }}
    />
    }