Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

anchor.tsx

207 lines6.2 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { useLayoutEffect, useRef, useState } from 'react'
3import { Link, useLocation, useNavigate } from '@tanstack/react-router'
4​
5export const Route = createFileRoute('/anchor')({
6 component: AnchorComponent,
7})
8​
9const anchors: Array<{
10 id: string
11 title: string
12 hashScrollIntoView?: boolean | ScrollIntoViewOptions
13}> = [
14 {
15 id: 'default-anchor',
16 title: 'Default Anchor',
17 },
18 {
19 id: 'false-anchor',
20 title: 'No Scroll Into View',
21 hashScrollIntoView: false,
22 },
23 {
24 id: 'smooth-scroll',
25 title: 'Smooth Scroll',
26 hashScrollIntoView: { behavior: 'smooth' },
27 },
28] as const
29​
30function AnchorSection({ id, title }: { id: string; title: string }) {
31 const [hasShown, setHasShown] = useState(false)
32 const elementRef = useRef<HTMLHeadingElement>(null)
33​
34 useLayoutEffect(() => {
35 const observer = new IntersectionObserver(
36 ([entry]) => {
37 if (!hasShown && entry.isIntersecting) {
38 setHasShown(true)
39 }
40 },
41 { threshold: 0.01 },
42 )
43​
44 const currentRef = elementRef.current
45 if (currentRef) {
46 observer.observe(currentRef)
47 }
48​
49 return () => {
50 if (currentRef) {
51 observer.unobserve(currentRef)
52 }
53 }
54 }, [hasShown])
55​
56 return (
57 <div id={id} className="p-2 min-h-dvh">
58 <h1 className="font-bold text-xl pt-10" ref={elementRef}>
59 {title}
60 {hasShown ? ' (shown)' : ''}
61 </h1>
62 </div>
63 )
65​
66function AnchorComponent() {
67 const navigate = useNavigate()
68 const location = useLocation()
69 const [withScroll, setWithScroll] = useState(true)
70​
71 return (
72 <div className="flex flex-col w-full">
73 <nav className="sticky top-0 z-10 p-2 bg-gray-50 dark:bg-gray-900 border-b">
74 <ul className="inline-flex gap-2">
75 {anchors.map((anchor) => (
76 <li key={anchor.id}>
77 <Link
78 from={Route.fullPath}
79 hash={anchor.id}
80 activeOptions={{ includeHash: true }}
81 activeProps={{
82 className: 'font-bold active',
83 }}
84 hashScrollIntoView={anchor.hashScrollIntoView}
85 >
86 {anchor.title}
87 </Link>
88 </li>
89 ))}
90 </ul>
91 </nav>
92 <main className="overflow-auto">
93 <form
94 className="p-2 space-y-2 min-h-dvh"
95 onSubmit={(event) => {
96 event.preventDefault()
97 event.stopPropagation()
98 const formData = new FormData(event.target as HTMLFormElement)
99​
100 const toHash = formData.get('hash') as string
101​
102 if (!toHash) {
103 return
104 }
105​
106 const hashScrollIntoView = withScroll
107 ? ({
108 behavior: formData.get('scrollBehavior') as ScrollBehavior,
109 block: formData.get('scrollBlock') as ScrollLogicalPosition,
110 inline: formData.get('scrollInline') as ScrollLogicalPosition,
111 } satisfies ScrollIntoViewOptions)
112 : false
113​
114 navigate({ hash: toHash, hashScrollIntoView })
115 }}
116 >
117 <h1 className="font-bold text-xl">Scroll with navigate</h1>
118 <div className="space-y-2">
119 <label>
120 <span>Target Anchor</span>
121 <select
122 className="border border-opacity-50 rounded-sm p-2 w-full"
123 defaultValue={location.hash || anchors[0].id}
124 name="hash"
125 >
126 {anchors.map((anchor) => (
127 <option key={anchor.id} value={anchor.id}>
128 {anchor.title}
129 </option>
130 ))}
131 </select>
132 </label>
133 <div>
134 <label>
135 <input
136 checked={withScroll}
137 onChange={(e) => setWithScroll(e.target.checked)}
138 type="checkbox"
139 />{' '}
140 Scroll Into View
141 </label>
142 </div>
143 </div>
144 {withScroll ? (
145 <>
146 <div className="space-y-2">
147 <label>
148 <span>Behavior</span>
149 <select
150 className="border border-opacity-50 rounded-sm p-2 w-full"
151 defaultValue="instant"
152 name="scrollBehavior"
153 >
154 <option value="instant">instant</option>
155 <option value="smooth">smooth</option>
156 <option value="auto">auto</option>
157 </select>
158 </label>
159 </div>
160​
161 <div className="space-y-2">
162 <label>
163 <span>Block</span>
164 <select
165 className="border border-opacity-50 rounded-sm p-2 w-full"
166 defaultValue="start"
167 name="scrollBlock"
168 >
169 <option value="start">start</option>
170 <option value="center">center</option>
171 <option value="end">end</option>
172 <option value="nearest">nearest</option>
173 </select>
174 </label>
175 </div>
176​
177 <div className="space-y-2">
178 <label>
179 <span>Inline</span>
180 <select
181 className="border border-opacity-50 rounded-sm p-2 w-full"
182 defaultValue="nearest"
183 name="scrollInline"
184 >
185 <option value="start">start</option>
186 <option value="center">center</option>
187 <option value="end">end</option>
188 <option value="nearest">nearest</option>
189 </select>
190 </label>
191 </div>
192 </>
193 ) : null}
194 <div>
195 <button className="bg-blue-500 rounded-sm p-2 uppercase text-white font-black disabled:opacity-50">
196 Navigate
197 </button>
198 </div>
199 </form>
200​
201 {anchors.map((anchor) => (
202 <AnchorSection key={anchor.id} id={anchor.id} title={anchor.title} />
203 ))}
204 </main>
205 </div>
206 )