forked from kriasoft/react-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseNavigate.ts
36 lines (30 loc) · 955 Bytes
/
useNavigate.ts
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
/* SPDX-FileCopyrightText: 2014-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */
import { To } from "history";
import * as React from "react";
import { useHistory } from "./useHistory";
function isLeftClickEvent(event: React.MouseEvent<HTMLElement>) {
return event.button === 0;
}
function isModifiedEvent(event: React.MouseEvent<HTMLElement>) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
export function useNavigate<T extends HTMLElement = HTMLAnchorElement>(): (
event: React.MouseEvent<T>
) => void {
const history = useHistory();
return React.useCallback(
(event: React.MouseEvent<T>): void => {
if (
event.defaultPrevented ||
isModifiedEvent(event) ||
!isLeftClickEvent(event)
) {
return;
}
event.preventDefault();
history.push(event.currentTarget.getAttribute("href") as To);
},
[history]
);
}