Open History to see the last commit
1'use client'
2β
3import * as React from 'react'
4import {
5 deepEqual,
6 functionalUpdate,
7 getUrlScheme,
8 isDangerousProtocol,
9 preloadWarning,
10 removeTrailingSlash,
11} from '@tanstack/router-core'
12import { isServer } from '@tanstack/router-core/isServer'
13import { useRouter } from './useRouter'
14import { createLinkScope, matchContext } from './matchContext'
15β
16import type {
17 ActiveOptions,
18 AnyRouter,
19 Constrain,
20 LinkOptions,
21 ParsedLocation,
22 RegisteredRouter,
23 RoutePaths,
24} from '@tanstack/router-core'
25import type { ReactNode } from 'react'
26import type {
27 ValidateLinkOptions,
28 ValidateLinkOptionsArray,
29} from './typePrimitives'
30β
31// Undefined active state marks an external or blocked link.
32// Keep that classification with the href instead of parsing it again on render.
33type LinkState = [href: string | undefined, isActive?: boolean]
34β
35// Keep referentially stable values while their contents are equal. Links
36// routinely pass inline `params` / `search` object literals, which would
37// otherwise change `dest` identity on every parent render, rebuild the
38// link state snapshot, and discard its memoized state. One ref holds all of
39// them; each entry is replaced only when its own contents change.
40//
41// The router reuses a built location for as long as it sees the same options
42// object, so the references returned here are its invalidation signal: pass a
43// new object to change a destination. Like every other React prop, an object
44// mutated in place is not re-read. `deepEqual` short-circuits on reference
45// equality, so an unchanged reference costs nothing.
46//
47// `explicitUndefined` is required: an explicit `undefined` clears an
48// inherited param or search key, so `{}` and `{ category: undefined }` build
49// different locations and must not be treated as equal here.
50function useStableValues<T extends ReadonlyArray<unknown>>(...values: T): T {
51 const ref = React.useRef<ReadonlyArray<unknown>>(values)
52 const stable = ref.current as Array<unknown>
53 values.forEach((value, index) => {
54 if (!deepEqual(stable[index], value, false, true)) {
55 stable[index] = value
56 }
57 })
58 return ref.current as T
59}
60β
61function preloadLink(router: AnyRouter, options: unknown) {
62 router.preloadRoute(options as any).catch((err) => {
63 console.warn(err)
64 console.warn(preloadWarning)
65 })
66}
67β
68function resolveExternalLink(
69 to: string | undefined,
70 protocolAllowlist: AnyRouter['protocolAllowlist'],
71): string | null | undefined {
72 const scheme = typeof to === 'string' && getUrlScheme(to)
73 if (!scheme) {
74 return undefined
75 }
76 if (!protocolAllowlist.has(scheme)) {
77 if (process.env.NODE_ENV !== 'production') {
78 console.warn(`Blocked Link with dangerous protocol: ${to}`)
79 }
80 return null
81 }
82 return to
83}
84β
85function resolveIsActive(
86 location: ParsedLocation,
87 next: ParsedLocation,
88 activeOptions: ActiveOptions | undefined,
89 basepath: string,
90): boolean {
91 const currentPath = removeTrailingSlash(location.pathname, basepath)
92 const nextPath = removeTrailingSlash(next.pathname, basepath)
93β
94 // Both modes compare normalized paths; fuzzy matches need a segment boundary.
95 if (
96 activeOptions?.exact
97 ? currentPath !== nextPath
98 : !(
99 currentPath.startsWith(nextPath) &&
100 (currentPath.length === nextPath.length ||
101 currentPath[nextPath.length] === '/')
102 )
103 ) {
104 return false
105 }
106β
107 if (activeOptions?.includeSearch ?? true) {
108 const searchTest = deepEqual(
109 location.search,
110 next.search,
111 !activeOptions?.exact,
112 activeOptions?.explicitUndefined,
113 )
114 if (!searchTest) {
115 return false
116 }
117 }
118β
119 return !activeOptions?.includeHash || location.hash === next.hash
120}
121β
122/**
123 * Build anchor-like props for declarative navigation and preloading.
124 *
125 * Returns stable `href`, event handlers and accessibility props derived from
126 * router options and active state. Used internally by `Link` and custom links.
127 *
128 * Options cover `to`, `params`, `search`, `hash`, `state`, `preload`,
129 * `activeProps`, `inactiveProps`, and more.
130 *
131 * @returns React anchor props suitable for `<a>` or custom components.
132 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLinkPropsHook
133 */
134export function useLinkProps<
135 TRouter extends AnyRouter = RegisteredRouter,
136 const TFrom extends string = string,
137 const TTo extends string | undefined = undefined,
138 const TMaskFrom extends string = TFrom,
139 const TMaskTo extends string = '',
140>(
141 options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
142 forwardedRef?: React.ForwardedRef<Element>,
143): React.ComponentPropsWithRef<'a'>
144/**
145 * `host` is what the props are rendered on: `'a'` for `Link` or the component
146 * given to `createLink`. `Link` never renders `type` and an anchor never
147 * receives `disabled`, so those are left out here rather than copied away
148 * from the result in the component. Stripped from the public declarations.
149 *
150 * @internal
151 */
152export function useLinkProps<
153 TRouter extends AnyRouter = RegisteredRouter,
154 const TFrom extends string = string,
155 const TTo extends string | undefined = undefined,
156 const TMaskFrom extends string = TFrom,
157 const TMaskTo extends string = '',
158>(
159 options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
160 forwardedRef: React.ForwardedRef<Element> | undefined,
161 host: 'a' | React.ElementType,
162): React.ComponentPropsWithRef<'a'>
163export function useLinkProps<
164 TRouter extends AnyRouter = RegisteredRouter,
165 const TFrom extends string = string,
166 const TTo extends string | undefined = undefined,
167 const TMaskFrom extends string = TFrom,
168 const TMaskTo extends string = '',
169>(
170 options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
171 forwardedRef?: React.ForwardedRef<Element>,
172 host?: 'a' | React.ElementType,
173): React.ComponentPropsWithRef<'a'> {
174 const router = useRouter()
175β
176 // ==========================================================================
177 // SERVER EARLY RETURN
178 // On the server, we return static props without any event handlers,
179 // effects, or client-side interactivity.
180 //
181 // For SSR parity (to avoid hydration errors), we still compute the link's
182 // active status on the server, but we avoid creating any router-state
183 // subscriptions by reading from the location store directly.
184 //
185 // Note: `location.hash` is not available on the server.
186 // ==========================================================================
187 // The expression must stay inlined in the `if` so bundlers fold the
188 // browser-build constant `isServer = false` and drop this server block,
189 // together with `getServerLinkProps` and the key sets only it references.
190 if (isServer ?? router.isServer) {
191 return getServerLinkProps(router, options, forwardedRef, host)
192 }
193β
194 // ==========================================================================
195 // CLIENT-ONLY CODE
196 // Everything below this point only runs on the client. The `isServer` check
197 // above is a compile-time constant that bundlers use for dead code elimination,
198 // so this entire section is removed from server bundles.
199 //
200 // We disable the rules-of-hooks lint rule because these hooks appear after
201 // an early return. This is safe because:
202 // 1. `isServer` is a compile-time constant from conditional exports
203 // 2. In server bundles, this code is completely eliminated by the bundler
204 // 3. In client bundles, `isServer` is `false`, so the early return never executes
205 // ==========================================================================
206β
207 // The link's own ref: the element for the viewport observer and the holder
208 // of a pending intent timer. A forwarded ref is filled alongside it by one
209 // callback, memoized on the forwarded ref so React re-attaches it (and
210 // notifies the consumer) only when their ref changes, not on every render.
211 // A cleanup returned by a consumer callback is passed through to React.
212 // eslint-disable-next-line react-hooks/rules-of-hooks
213 const innerRef: LinkRef = React.useRef<Element>(null)
214 // eslint-disable-next-line react-hooks/rules-of-hooks
215 const mergedRef = React.useCallback(
216 (element: Element | null) => {
217 innerRef.current = element
218 if (typeof forwardedRef === 'function') {
219 return forwardedRef(element)
220 }
221 if (forwardedRef) {
222 forwardedRef.current = element
223 }
224 return undefined
225 },
226 [forwardedRef],
227 )
228β
229 const {
230 activeOptions,
231 to,
232 preload: userPreload,
233 preloadDelay: userPreloadDelay,
234 disabled,
235 target,
236 onClick,
237 onBlur,
238 onFocus,
239 onMouseEnter,
240 onMouseLeave,
241 onTouchStart,
242 } = options as typeof options & { to?: string }
243β
244 // eslint-disable-next-line react-hooks/rules-of-hooks
245 const [stableSearch, stableParams, stableActiveOptions] = useStableValues(
246 options.search,
247 options.params,
248 activeOptions,
249 )
250 // The links of a route share its location source. Links outside every
251 // match share one that never departs.
252 // eslint-disable-next-line react-hooks/rules-of-hooks
253 const routeId = React.useContext(matchContext)
254 const scope = ((router.stores._linkScopes ??= {})[routeId!] ??=
255 createLinkScope(router, routeId))
256β
257 // `dest` is the link's own copy of the options from the render that last
258 // changed the link: one stable object per link lets the router reuse
259 // location-independent results. It also carries the location the link
260 // displays, so clicks and preloads go where its href points.
261 // The snapshot depends only on the scope's location: it derives once per
262 // location so React can bail out on an unchanged state, and derives eagerly
263 // inside the scope's notification.
264 // eslint-disable-next-line react-hooks/rules-of-hooks
265 const [dest, getLinkState, getHydrationState] = React.useMemo(() => {
266 // Direct destinations and the router's allowlist are stable for this snapshot.
267 const directExternalLink = resolveExternalLink(to, router.protocolAllowlist)
268 if (directExternalLink !== undefined) {
269 const state: LinkState = [directExternalLink ?? undefined]
270 return [options, () => state] as const
271 }
272β
273 const dest = { ...options } as any
274 let source: ParsedLocation | undefined
275 let state: LinkState
276 let hydrationState: LinkState | undefined
277β
278 const getLinkState = (): LinkState => {
279 // Read the location once and record it only after deriving: a
280 // derivation that throws is retried instead of caching its state.
281 const location = scope[0 /* getSource */]()
282 if (location !== source) {
283 dest._fromLocation = location
284 const next = router.buildLocation(dest)
285β
286 // History formatters can depend on the current browser URL (hash history).
287 const href = getHrefOption(next, router, disabled)
288 // Internal and disabled links can be active; external and blocked
289 // links have no active state.
290 const isActive =
291 disabled || (href && !getUrlScheme(href))
292 ? resolveIsActive(
293 location,
294 next,
295 stableActiveOptions,
296 router.basepath,
297 )
298 : undefined
299 // Keep the state while it is equal so React can bail out.
300 if (
301 !state ||
302 state[0 /* href */] !== href ||
303 state[1 /* isActive */] !== isActive
304 ) {
305 state = [href, isActive]
306 }
307 source = location
308 }
309 return state
310 }
311β
312 return [
313 dest,
314 getLinkState,
315 // Hydration renders the server's markup, which has no hash, so an active
316 // hash-sensitive link hydrates inactive and React rerenders it after.
317 stableActiveOptions?.includeHash &&
318 ((): LinkState => {
319 const state = getLinkState()
320 return state[1 /* isActive */]
321 ? (hydrationState ??= [state[0 /* href */], false])
322 : state
323 }),
324 ] as const
325 // eslint-disable-next-line react-hooks/exhaustive-deps
326 }, [
327 router,
328 scope,
329 options.from,
330 options.hash,
331 options.href,
332 to,
333 stableSearch,
334 stableParams,
335 options.state,
336 options.mask,
337 options.unsafeRelative,
338 stableActiveOptions,
339 disabled,
340 ])
341β
342 // eslint-disable-next-line react-hooks/rules-of-hooks
343 const [href, isActive] = React.useSyncExternalStore(
344 scope[1 /* subscribe */],
345 getLinkState,
346 getHydrationState || getLinkState,
347 )
348 const externalLink = isActive === undefined && href
349 const linkDisabled = disabled || href === undefined
350β
351 // eslint-disable-next-line react-hooks/rules-of-hooks
352 const hasRenderFetched = React.useRef(false)
353β
354 const preload =
355 options.reloadDocument || externalLink || linkDisabled
356 ? false
357 : (userPreload ?? router.options.defaultPreload)
358 const preloadDelay =
359 userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0
360β
361 // `preloadRoute` builds the location itself and only reads the options, so
362 // `dest` goes through as-is.
363 // eslint-disable-next-line react-hooks/rules-of-hooks
364 const enqueuePreload = React.useCallback(
365 (e?: React.MouseEvent | React.FocusEvent | IntersectionObserverEntry) => {
366 const isIntersecting = (e as IntersectionObserverEntry | undefined)
367 ?.isIntersecting
368 if (!(isIntersecting ?? preload === 'intent')) {
369 if (isIntersecting === false) {
370 cancelPreload(innerRef)
371 }
372 return
373 }
374β
375 if (!preloadDelay) {
376 preloadLink(router, dest)
377 return
378 }
379β
380 innerRef.t ??= setTimeout(() => {
381 innerRef.t = undefined
382 preloadLink(router, dest)
383 }, preloadDelay)
384 },
385 [router, dest, innerRef, preload, preloadDelay],
386 )
387β
388 // Preload side effects: `render` preloads once per link, `viewport` watches
389 // the element. The cleanup also cancels a pending intent timer.
390 // eslint-disable-next-line react-hooks/rules-of-hooks
391 React.useEffect(() => {
392 // Disabled preloading creates neither an observer nor an intent timer.
393 if (!preload) {
394 return
395 }
396 if (preload === 'render' && !hasRenderFetched.current) {
397 hasRenderFetched.current = true
398 preloadLink(router, dest)
399 }
400 let active = true
401 let observer: IntersectionObserver | undefined
402 if (
403 preload === 'viewport' &&
404 innerRef.current &&
405 typeof IntersectionObserver === 'function'
406 ) {
407 observer = new IntersectionObserver(
408 (entries) => {
409 // A queued observer notification can arrive after disconnect().
410 if (active) {
411 enqueuePreload(entries.pop())
412 }
413 },
414 { rootMargin: '100px' },
415 )
416 observer.observe(innerRef.current)
417 }
418 return () => {
419 active = false
420 observer?.disconnect()
421 cancelPreload(innerRef)
422 }
423 }, [router, dest, preload, enqueuePreload, innerRef])
424β
425 const props = collectElementProps(options, host)
426 props.ref = forwardedRef ? mergedRef : innerRef
427 // External links get no router behavior: element props pass through as given.
428 if (externalLink) {
429 props.href = externalLink
430 return props
431 }
432β
433 // The click handler
434 const handleClick = (e: React.MouseEvent) => {
435 // The element's own target attribute is the fallback.
436 const effectiveTarget =
437 target ??
438 (e.currentTarget as HTMLAnchorElement | SVGAElement).getAttribute(
439 'target',
440 )
441β
442 if (
443 !linkDisabled &&
444 !(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) &&
445 !e.defaultPrevented &&
446 (!effectiveTarget || effectiveTarget === '_self') &&
447 e.button === 0
448 ) {
449 e.preventDefault()
450 cancelPreload(innerRef)
451β
452 // The current options carry the navigation controls; `dest` only
453 // contributes the location the link displays. Navigation builds again
454 // to run `validateSearch` before committing.
455 router.navigate({ ...options, _fromLocation: dest._fromLocation })
456 }
457 }
458β
459 const handleTouchStart = () => {
460 if (preload === 'intent') {
461 preloadLink(router, dest)
462 }
463 }
464β
465 const handleLeave = () => {
466 if (preload === 'intent') {
467 cancelPreload(innerRef)
468 }
469 }
470β
471 props.onClick = composeHandlers(onClick, handleClick)
472 props.onBlur = composeHandlers(onBlur, handleLeave)
473 props.onFocus = composeHandlers(onFocus, enqueuePreload)
474 props.onMouseEnter = composeHandlers(onMouseEnter, enqueuePreload)
475 props.onMouseLeave = composeHandlers(onMouseLeave, handleLeave)
476 props.onTouchStart = composeHandlers(onTouchStart, handleTouchStart)
477 return applyLinkState(props, options, isActive, href, linkDisabled, host)
478}
479β
480const STATIC_EMPTY_OBJECT = {}
481const STATIC_ACTIVE_OBJECT = { className: 'active' }
482// Options the router consumes; they never reach the element. Every other
483// option is an element prop and passes through.
484const ROUTER_OPTION_KEYS = /* @__PURE__ */ new Set([
485 'to',
486 'params',
487 'search',
488 'hash',
489 'state',
490 'mask',
491 'from',
492 'unsafeRelative',
493 'reloadDocument',
494 'preload',
495 'preloadDelay',
496 'preloadIntentProximity',
497 'hashScrollIntoView',
498 'replace',
499 'startTransition',
500 'resetScroll',
501 'viewTransition',
502 'ignoreBlocker',
503 'activeProps',
504 'inactiveProps',
505 'activeOptions',
506 '_asChild',
507])
508β
509// Copies the element props. An object rest would test every key against the
510// whole exclusion list; the key set is much cheaper. `Link` hosts never render
511// `type`, and an anchor has no `disabled` attribute.
512function collectElementProps(
513 options: object,
514 host: 'a' | React.ElementType | undefined,
515): Record<string, unknown> {
516 const props: Record<string, unknown> = {}
517 for (const key in options) {
518 if (
519 ROUTER_OPTION_KEYS.has(key) ||
520 (key === 'type' && host !== undefined) ||
521 (key === 'disabled' && host === 'a')
522 ) {
523 continue
524 }
525 props[key] = (options as Record<string, unknown>)[key]
526 }
527 return props
528}
529β
530// Finishes a router-controlled link: the selected state props, then the
531// routing attributes. This is the one place that defines precedence: state
532// props override element props, `ref` and handlers; `href`, `disabled`,
533// `target` and the merged class and style always win.
534function applyLinkState(
535 props: Record<string, unknown>,
536 options: {
537 activeProps?: unknown
538 inactiveProps?: unknown
539 className?: string
540 style?: React.CSSProperties
541 target?: string
542 },
543 isActive: boolean | undefined,
544 href: string | undefined,
545 linkDisabled: boolean,
546 host: 'a' | React.ElementType | undefined,
547): React.ComponentPropsWithRef<'a'> {
548 const { activeProps, inactiveProps, className, style, target } = options
549 const stateProps: React.HTMLAttributes<HTMLAnchorElement> =
550 functionalUpdate((isActive ? activeProps : inactiveProps) as any, {}) ??
551 (isActive ? STATIC_ACTIVE_OBJECT : STATIC_EMPTY_OBJECT)
552 Object.assign(props, stateProps)
553 props.href = href
554 if (host !== 'a') {
555 props.disabled = linkDisabled
556 }
557 props.target = target
558 // Merge class and style with the state's. Links without either keep their
559 // props as given and carry no `undefined` keys.
560 const stateStyle = stateProps.style
561 if (style || stateStyle) {
562 props.style =
563 style && stateStyle ? { ...style, ...stateStyle } : style || stateStyle
564 }
565 const stateClassName = stateProps.className
566 if (className || stateClassName) {
567 props.className = className
568 ? stateClassName
569 ? `${className} ${stateClassName}`
570 : className
571 : stateClassName
572 }
573 if (linkDisabled) {
574 props.role = 'link'
575 props['aria-disabled'] = true
576 }
577 if (isActive) {
578 props['data-status'] = 'active'
579 props['aria-current'] = 'page'
580 }
581 return props
582}
583β
584// Server render of a Link: static props only, no hooks. Only server bundles
585// keep this function; the `isServer` check that calls it folds away on the client.
586function getServerLinkProps(
587 router: AnyRouter,
588 options: any,
589 forwardedRef: React.ForwardedRef<Element> | undefined,
590 host: 'a' | React.ElementType | undefined,
591): React.ComponentPropsWithRef<'a'> {
592 const { to, disabled, activeOptions } = options as {
593 to: string | undefined
594 disabled: boolean | undefined
595 activeOptions: ActiveOptions | undefined
596 }
597β
598 const directExternalLink = resolveExternalLink(to, router.protocolAllowlist)
599β
600 // Direct-scheme links need no route resolution. Blocked links still use
601 // the shared inactive-prop merge so their server and client markup agree.
602 const next =
603 directExternalLink === undefined ? router.buildLocation(options) : undefined
604β
605 const hrefOption = next
606 ? getHrefOption(next, router, disabled)
607 : (directExternalLink ?? undefined)
608 const linkDisabled = disabled || !hrefOption
609β
610 const externalLink =
611 directExternalLink ??
612 (hrefOption && getUrlScheme(hrefOption) ? hrefOption : undefined)
613β
614 const props = collectElementProps(options, host)
615 props.ref = forwardedRef
616 if (externalLink) {
617 props.href = externalLink
618 return props
619 }
620β
621 const blockedLink = !disabled && !hrefOption
622 // Hash is not available on the server: hash-sensitive links are inactive.
623 const isActive =
624 !!next &&
625 !blockedLink &&
626 !activeOptions?.includeHash &&
627 resolveIsActive(
628 router.stores.location.get(),
629 next,
630 activeOptions,
631 router.basepath,
632 )
633 return applyLinkState(
634 props,
635 options,
636 isActive,
637 hrefOption,
638 linkDisabled,
639 host,
640 )
641}
642β
643// A Link's own ref also holds its pending intent preload timer.
644type LinkRef = React.RefObject<Element | null> & {
645 t?: ReturnType<typeof setTimeout>
646}
647const cancelPreload = (ref: LinkRef) => {
648 clearTimeout(ref.t)
649 ref.t = undefined
650}
651β
652export const composeHandlers = (
653 first: React.EventHandler<any> | undefined,
654 second: React.EventHandler<any>,
655) => {
656 if (!first) {
657 return second
658 }
659β
660 // The first guard skips user handlers for already-prevented events; the second
661 // lets user handlers prevent the internal handler from running.
662 return (event: React.SyntheticEvent) =>
663 event.defaultPrevented ||
664 (first(event), event.defaultPrevented || second(event))
665}
666β
667function getHrefOption(
668 next: ParsedLocation,
669 router: AnyRouter,
670 disabled: boolean | undefined,
671) {
672 if (disabled) {
673 return undefined
674 }
675 const location = next.maskedLocation ?? next
676 // A rewritten external URL must bypass history's relative-path formatting.
677 const href = location.external
678 ? location.publicHref
679 : router.history.createHref(location.publicHref) || '/'
680 if (
681 (location.external || href !== location.publicHref) &&
682 isDangerousProtocol(href, router.protocolAllowlist)
683 ) {
684 if (process.env.NODE_ENV !== 'production') {
685 console.warn(`Blocked Link with dangerous protocol: ${href}`)
686 }
687 return undefined
688 }
689 return href
690}
691β
692type UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements
693 ? React.JSX.IntrinsicElements[TComp]
694 : TComp extends React.ComponentType<any>
695 ? React.ComponentPropsWithoutRef<TComp> &
696 React.RefAttributes<React.ComponentRef<TComp>>
697 : never
698β
699export type UseLinkPropsOptions<
700 TRouter extends AnyRouter = RegisteredRouter,
701 TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
702 TTo extends string | undefined = '.',
703 TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
704 TMaskTo extends string = '.',
705> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
706 UseLinkReactProps<'a'>
707β
708export type ActiveLinkOptions<
709 TComp = 'a',
710 TRouter extends AnyRouter = RegisteredRouter,
711 TFrom extends string = string,
712 TTo extends string | undefined = '.',
713 TMaskFrom extends string = TFrom,
714 TMaskTo extends string = '.',
715> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
716 ActiveLinkOptionProps<TComp>
717β
718type ActiveLinkProps<TComp> = Partial<
719 LinkComponentReactProps<TComp> & {
720 [key: `data-${string}`]: unknown
721 }
722>
723β
724export interface ActiveLinkOptionProps<TComp = 'a'> {
725 /**
726 * A function that returns additional props for the `active` state of this link.
727 * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)
728 */
729 activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
730 /**
731 * A function that returns additional props for the `inactive` state of this link.
732 * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)
733 */
734 inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
735}
736β
737export type LinkProps<
738 TComp = 'a',
739 TRouter extends AnyRouter = RegisteredRouter,
740 TFrom extends string = string,
741 TTo extends string | undefined = '.',
742 TMaskFrom extends string = TFrom,
743 TMaskTo extends string = '.',
744> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
745 LinkPropsChildren
746β
747export interface LinkPropsChildren {
748 // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns
749 children?:
750 | React.ReactNode
751 | ((state: { isActive: boolean }) => React.ReactNode)
752}
753β
754type LinkComponentReactProps<TComp> = Omit<
755 UseLinkReactProps<TComp>,
756 keyof CreateLinkProps
757>
758β
759export type LinkComponentProps<
760 TComp = 'a',
761 TRouter extends AnyRouter = RegisteredRouter,
762 TFrom extends string = string,
763 TTo extends string | undefined = '.',
764 TMaskFrom extends string = TFrom,
765 TMaskTo extends string = '.',
766> = LinkComponentReactProps<TComp> &
767 LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>
768β
769export type CreateLinkProps = LinkProps<
770 any,
771 any,
772 string,
773 string,
774 string,
775 string
776>
777β
778export type LinkComponent<
779 in out TComp,
780 in out TDefaultFrom extends string = string,
781> = <
782 TRouter extends AnyRouter = RegisteredRouter,
783 const TFrom extends string = TDefaultFrom,
784 const TTo extends string | undefined = undefined,
785 const TMaskFrom extends string = TFrom,
786 const TMaskTo extends string = '',
787>(
788 props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
789) => React.ReactElement
790β
791export interface LinkComponentRoute<
792 in out TDefaultFrom extends string = string,
793> {
794 defaultFrom: TDefaultFrom;
795 <
796 TRouter extends AnyRouter = RegisteredRouter,
797 const TTo extends string | undefined = undefined,
798 const TMaskTo extends string = '',
799 >(
800 props: LinkComponentProps<
801 'a',
802 TRouter,
803 this['defaultFrom'],
804 TTo,
805 this['defaultFrom'],
806 TMaskTo
807 >,
808 ): React.ReactElement
809}
810β
811/**
812 * Creates a typed Link-like component that preserves TanStack Router's
813 * navigation semantics and type-safety while delegating rendering to the
814 * provided host component.
815 *
816 * Useful for integrating design system anchors/buttons while keeping
817 * router-aware props (eg. `to`, `params`, `search`, `preload`).
818 *
819 * @param Comp The host component to render (eg. a design-system Link/Button)
820 * @returns A router-aware component with the same API as `Link`.
821 * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-link
822 */
823export function createLink<const TComp>(
824 Comp: Constrain<TComp, any, (props: CreateLinkProps) => ReactNode>,
825): LinkComponent<TComp> {
826 return React.forwardRef(function CreatedLink(props, ref) {
827 return <Link {...(props as any)} _asChild={Comp} ref={ref} />
828 }) as any
829}
830β
831/**
832 * A strongly-typed anchor component for declarative navigation.
833 * Handles path, search, hash and state updates with optional route preloading
834 * and active-state styling.
835 *
836 * Props:
837 * - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false)
838 * - `preloadDelay`: Delay in ms before preloading on focus, hover, or viewport entry
839 * - `activeProps`/`inactiveProps`: Additional props merged when link is active/inactive
840 * - `resetScroll`/`hashScrollIntoView`: Control scroll behavior on navigation
841 * - `viewTransition`/`startTransition`: Use View Transitions/React transitions for navigation
842 * - `ignoreBlocker`: Bypass registered blockers
843 *
844 * @returns An anchor-like element that navigates without full page reloads.
845 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkComponent
846 */
847export const Link: LinkComponent<'a'> = React.memo(
848 React.forwardRef<Element, any>((props, ref) => {
849 const host = props._asChild || 'a'
850 const linkProps = useLinkProps(props as any, ref, host)
851β
852 const children =
853 typeof props.children === 'function'
854 ? props.children({
855 isActive: (linkProps as any)['data-status'] === 'active',
856 })
857 : props.children
858β
859 return React.createElement(host, linkProps, children)
860 }),
861 areLinkPropsEqual,
862) as any
863β
864// A Link's output depends only on its props, the router context and its
865// route's location source, which React tracks for memoized components, so a parent
866// re-render with equal props can skip it. Router options are compared by
867// value: destinations are usually inline object literals. Element props
868// (`children`, handlers, `style`, ...) are compared by reference only, since
869// they may hold arbitrary (even cyclic) data.
870function areLinkPropsEqual(
871 prev: Record<string, unknown>,
872 next: Record<string, unknown>,
873): boolean {
874 let extraKeys = 0
875 for (const key in next) {
876 extraKeys++
877 if (prev[key] === next[key]) {
878 continue
879 }
880 if (
881 !ROUTER_OPTION_KEYS.has(key) ||
882 !deepEqual(prev[key], next[key], false, true)
883 ) {
884 return false
885 }
886 }
887 for (const _key in prev) {
888 extraKeys--
889 }
890 return extraKeys === 0
891}
892β
893export type LinkOptionsFnOptions<
894 TOptions,
895 TComp,
896 TRouter extends AnyRouter = RegisteredRouter,
897> =
898 TOptions extends ReadonlyArray<any>
899 ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>
900 : ValidateLinkOptions<TRouter, TOptions, string, TComp>
901β
902export type LinkOptionsFn<TComp> = <
903 const TOptions,
904 TRouter extends AnyRouter = RegisteredRouter,
905>(
906 options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,
907) => TOptions
908β
909/**
910 * Validate and reuse navigation options for `Link`, `navigate` or `redirect`.
911 * Accepts a literal options object and returns it typed for later spreading.
912 * @example
913 * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })
914 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions
915 */
916export const linkOptions: LinkOptionsFn<'a'> = (options) => {
917 return options as any
918}
919β
920/**
921 * Type-check a literal object for use with `Link`, `navigate` or `redirect`.
922 * Use to validate and reuse navigation options across your app.
923 * @example
924 * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })
925 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions
926 */