Navigate to a View
In this guide, you’ll learn how to use <NavLink> component and useNavigate hook of react-router to navigate between views.
Navigating Between Views Using Links
The <NavLink> component from react-router renders a clickable link for navigation. In HTML, it corresponds to an anchor (<a>) element.
|
Tip
| Links are preferable to programmatic navigation because they improve accessibility. They also allow users to open links in new browser tabs. |
For example, to create a link to a view located at /some-view, you can use the following code:
Source code
tsx
import { NavLink } from 'react-router';
<NavLink to="/some-view">Some View</NavLink>This code creates a clickable link labeled "Some View" that navigates to the /some-view route when clicked.
Programmatic Navigation
In some scenarios, you may need to navigate between views programmatically, such as after a form submission or in response to user interactions. For this you can use the useNavigate hook of react-router to achieve this.
Here’s an example of how to use useNavigate for programmatic navigation:
Source code
tsx
import { useNavigate } from 'react-router';
function MyComponent() {
const navigate = useNavigate();
const handleClick = () => {
navigate('/target-view');
};
return (
<button onClick={handleClick}>
Go to Target View
</button>
);
}In the above example, clicking the button navigates the user to /target-view.