Navigating programmatically

Sometimes, it is necessary to do navigation programmatically. Follow these steps to programmatically navigate to the ask page when the Ask a question button is clicked:

  1. Import RouteComponentProps from React Router into HomePage.tsx:
import { RouteComponentProps } from 'react-router-dom';

This will give us access to a history object, which can be used to programmatically navigate.

The history object in React Router keeps track of the locations that have been visited in the app and contains quite a few different properties and methods. The push method pushes a new entry into the history stack and performs navigation to the location that's passed in as a parameter.
  1. We are going to use RouteComponentProps as the props type for HomePage, so let's import the FC generic type from React: 
import { useEffect, useState, FC } from 'react';
  1. Now, we can specify RouteComponentProps as the props type for HomePage and also destructure the history prop:
export const HomePage:FC<RouteComponentProps> = ({ history }) => { ... }
  1. In handleAskQuestionClick, we can replace the console.log statement with the navigation now:
const handleAskQuestionClick = () => {
history.push('/ask');
};
  1. In the running app, if we give this a try and click the Ask a question button, it will successfully navigate to the ask page.

So, we can declaratively navigate by using the Link component and programmatically navigate using the history object in React Router. In the next section, we are going to use the Link component again to perform navigation to the question page when a question is clicked on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.83.105