Navigating programmatically
React Router’s Link
and NavLink
components allow declarative navigation. However, sometimes we must navigate imperatively – in fact, this would be useful for the search feature in our app to navigate to the products list page. In this section, we will learn how to programmatically navigate with React Router and use this to complete the app’s search feature. Carry out the following steps:
- Open
Header.tsx
and add import theuseNavigate
hook from React Router:import {
NavLink,
Link,
useSearchParams,
useNavigate
} from 'react-router-dom';
The useNavigate
hook returns a function we can use to perform programmatic navigation.