-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathEuiCustomLink.tsx
More file actions
48 lines (37 loc) · 1.35 KB
/
EuiCustomLink.tsx
File metadata and controls
48 lines (37 loc) · 1.35 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
import React from "react";
import { EuiLink, type EuiLinkAnchorProps } from "@elastic/eui";
import { useNavigate, useHref, type To } from "react-router-dom";
interface EuiCustomLinkProps extends Omit<EuiLinkAnchorProps, "href"> {
to: To;
}
const isModifiedEvent = (event: React.MouseEvent) =>
!!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
const isLeftClickEvent = (event: React.MouseEvent) => event.button === 0;
const isTargetBlank = (event: React.MouseEvent) => {
const target = (event.target as Element).getAttribute("target");
return target && target !== "_self";
};
export default function EuiCustomLink({ to, ...rest }: EuiCustomLinkProps) {
// This is the key!
const navigate = useNavigate();
const onClick: React.MouseEventHandler<HTMLAnchorElement> = (event) => {
if (event.defaultPrevented) {
return;
}
// Let the browser handle links that open new tabs/windows
if (
isModifiedEvent(event) ||
!isLeftClickEvent(event) ||
isTargetBlank(event)
) {
return;
}
// Prevent regular link behavior, which causes a browser refresh.
event.preventDefault();
// Push the route to the history.
navigate(to);
};
// Generate the correct link href (with basename accounted for)
const href = useHref(to);
return <EuiLink {...rest} href={href} onClick={onClick} />;
}