UNPKG

2.53 kB Markdown View Raw
1---
2title: Navigating
3order: 3
4---
5
6# Navigating
7
8[MODES: declarative]
9
10## Introduction
11
12Users navigate your application with `<Link>`, `<NavLink>`, and `useNavigate`.
13
14## NavLink
15
16This component is for navigation links that need to render an active state.
17
18```tsx
19import { NavLink } from "react-router";
20
21export function MyAppNav() {
22 return (
23 <nav>
24 <NavLink to="/" end>
25 Home
26 </NavLink>
27 <NavLink to="/trending" end>
28 Trending Concerts
29 </NavLink>
30 <NavLink to="/concerts">All Concerts</NavLink>
31 <NavLink to="/account">Account</NavLink>
32 </nav>
33 );
34}
35```
36
37Whenever a `NavLink` is active, it will automatically have an `.active` class name for easy styling with CSS:
38
39```css
40a.active {
41 color: red;
42}
43```
44
45It also has callback props on `className`, `style`, and `children` with the active state for inline styling or conditional rendering:
46
47```tsx
48// className
49<NavLink
50 to="/messages"
51 className={({ isActive }) =>
52 isActive ? "text-red-500" : "text-black"
53 }
54>
55 Messages
56</NavLink>
57```
58
59```tsx
60// style
61<NavLink
62 to="/messages"
63 style={({ isActive }) => ({
64 color: isActive ? "red" : "black",
65 })}
66>
67 Messages
68</NavLink>
69```
70
71```tsx
72// children
73<NavLink to="/message">
74 {({ isActive }) => (
75 <span className={isActive ? "active" : ""}>
76 {isActive ? "👉" : ""} Tasks
77 </span>
78 )}
79</NavLink>
80```
81
82## Link
83
84Use `<Link>` when the link doesn't need active styling:
85
86```tsx
87import { Link } from "react-router";
88
89export function LoggedOutMessage() {
90 return (
91 <p>
92 You've been logged out.{" "}
93 <Link to="/login">Login again</Link>
94 </p>
95 );
96}
97```
98
99## useNavigate
100
101This hook allows the programmer to navigate the user to a new page without the user interacting.
102
103For normal navigation, it's best to use `Link` or `NavLink`. They provide a better default user experience like keyboard events, accessibility labeling, "open in new window", right click context menus, etc.
104
105Reserve usage of `useNavigate` to situations where the user is _not_ interacting but you need to navigate, for example:
106
107- After a form submission completes
108- Logging them out after inactivity
109- Timed UIs like quizzes, etc.
110
111```tsx
112import { useNavigate } from "react-router";
113
114export function LoginPage() {
115 let navigate = useNavigate();
116
117 return (
118 <>
119 <MyHeader />
120 <MyLoginForm
121 onSuccess={() => {
122 navigate("/dashboard");
123 }}
124 />
125 <MyFooter />
126 </>
127 );
128}
129```
130
131---
132
133Next: [Url values](./url-values)