简体   繁体   中英

Making entire table row clickable using React Router Link

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. 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 }} /> }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM