React Table Navigate on Row Click
Each table row in our missions table will link to a page for that mission. The url structure of that page will be /missions/:id
- where the id is the mission Id of that particular mission. In order to link there, we will use React Router's useNavigate
hook. Calling this hook at the top of our functional component will give us the navigate
method.
We'll add an onClick
handler here with a function navigateToMission
which we define inside our MissionRow
component. Finally, inside here we will call navigate
with a template literal /missions/${id}
to inject the ID into our string.
The end result here is that when you click on a row, we will navigate to that mission. Although, we do not have a route defined inside our Router, so we will get the NotFound route for now until we fix this in the next lecture.
Your mission: Fix the routing issue.
import styled from "styled-components"; import { useNavigate } from "react-router-dom"; const StyledTable = styled.div` display: grid; gap: 8px; grid-auto-rows: min-content; min-height: 300px; `; const StyledTableRow = styled.div` display: grid; height: 30px; grid-template-columns: 180px 1fr 80px; cursor: pointer; align-items: center; padding: 4px; &:hover { background-color: lightgray; } `; const TableCell = styled.div` text-overflow: ellipsis; white-space: nowrap; overflow: hidden; ${({ justifyRight }) => justifyRight && ` justify-self: right; `} `; function MissionRow({ data: { id, title, description, created_at } }) { const navigate = useNavigate(); function navigateToMission() { navigate(`/missions/${id}`); } return ( <StyledTableRow onClick={navigateToMission}> <TableCell> {title} </TableCell> <TableCell> {description} </TableCell> <TableCell justifyRight> {created_at} </TableCell> </StyledTableRow> ); } function MissionsTable({ missions }) { return ( <StyledTable> {missions.map((data) => ( <MissionRow key={data.title} data={data} /> ))} </StyledTable> ); } export default MissionsTable;