-
-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathLink.tsx
More file actions
55 lines (49 loc) · 1.57 KB
/
Link.tsx
File metadata and controls
55 lines (49 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import * as React from 'react';
import { RouterContext } from './context';
/**
* @ignore - internal component.
*/
export interface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
/*
* "replace" will replace the history stack with the URL being navigated to
* "push" will push the URL being navigated to as a new entry onto the history stack
* "auto" is the default and the mimics the "push" behaviour
*/
history?: 'auto' | 'push' | 'replace';
href: string;
}
export const DefaultLink = React.forwardRef(function Link(
props: LinkProps,
ref: React.ForwardedRef<HTMLAnchorElement>,
) {
const { children, href, onClick, history, ...rest } = props;
const routerContext = React.useContext(RouterContext);
const handleLinkClick = React.useMemo(() => {
if (!routerContext) {
return onClick;
}
return (event: React.MouseEvent<HTMLAnchorElement>) => {
event.preventDefault();
const url = new URL(event.currentTarget.href);
routerContext.navigate(url.pathname + url.search + url.hash, { history });
onClick?.(event);
};
}, [routerContext, onClick, history]);
return (
<a ref={ref} href={href} {...rest} onClick={handleLinkClick}>
{children}
</a>
);
});
export const Link = React.forwardRef(function Link(
props: LinkProps,
ref: React.ForwardedRef<HTMLAnchorElement>,
) {
const routerContext = React.useContext(RouterContext);
const LinkComponent = routerContext?.Link ?? DefaultLink;
return (
<LinkComponent ref={ref} {...props}>
{props.children}
</LinkComponent>
);
});