Let's carry out the following steps to add the question page route:
- In App.tsx, import the QuestionPage component we created earlier in this chapter:
import { QuestionPage } from './QuestionPage';
- In the App component's JSX, add a Route component for navigation to the question page:
<Switch>
<Redirect from="/home" to="/" />
<Route exact path="/" component={HomePage} />
<Route path="/search" component={SearchPage} />
<Route path="/ask" component={AskPage} />
<Route path="/signin" component={SignInPage} />
<Route path="/questions/:questionId" component={QuestionPage} />
<Route component={NotFoundPage} />
</Switch>
Note that the path we entered contains questionId at the end.
- Let's go to QuestionPage.tsx and import RouteComponentProps from React Router:
import { RouteComponentProps } from 'react-router-dom';
- Import the FC generic type from React as well:
import React, { FC } from 'react';
- Specify RouteComponentProps as the props type for QuestionPage and also destructure the match prop:
interface RouteParams {
questionId: string;
}
export const QuestionPage: FC<RouteComponentProps<RouteParams>> = ({
match
}) => <Page>Question Page</Page>;
We have defined the type for the route parameters in a RouteParams interface and passed this into the generic parameter for RouteComponentProps. We have destructured the match property that React Router gives the component. This will give us strongly typed access to the questionId route parameter.
- For now, we are going to output the questionId on the page as follows in the JSX:
<Page>Question Page {match.params.questionId}</Page>;
We access the questionId route parameter from the params property, which can be found in the match property we destructured in the last step. We'll come back and fully implement the question page in Chapter 5, Working with Forms. For now, we are going to link to this page from the Question component.
- So, in Question.tsx, add the following import statement to import the Link component:
import { Link } from 'react-router-dom';
- Now, we can wrap a Link around the title text in the Question JSX while specifying the path to navigate to:
<div
css={css`
padding: 10px 0px;
font-size: 19px;
`}
>
<Link
css={css`
text-decoration: none;
color: ${gray2};
`}
to={`questions/${data.questionId}`}
>
{data.title}
</Link>
</div>
- Go to the running app and try clicking on an unanswered question. It will successfully navigate to the question page, showing the correct questionId:
So, we implement routing parameters by defining variables in the route path with a colon in front and then picking the variable up in the match.params object in RouteComponentProps.