-
Notifications
You must be signed in to change notification settings - Fork 841
/
routing.js
48 lines (38 loc) · 1.21 KB
/
routing.js
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
// See `/wiki/react-router.md`
const isModifiedEvent = (event) =>
!!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
const isLeftClickEvent = (event) => event.button === 0;
const resolveToLocation = (to, router) =>
typeof to === 'function' ? to(router.location) : to;
let router;
export const registerRouter = (reactRouter) => {
router = reactRouter;
};
/**
* The logic for generating hrefs and onClick handlers from the `to` prop is largely borrowed from
* https://github.com/ReactTraining/react-router/blob/v3/modules/Link.js.
*/
export const getRouterLinkProps = (to) => {
const location = resolveToLocation(to, router);
const href = router.history.createHref({
pathname: location,
search: '',
hash: '',
});
const onClick = (event) => {
if (event.defaultPrevented) {
return;
}
// If target prop is set (e.g. to "_blank"), let browser handle link.
if (event.target.getAttribute('target')) {
return;
}
if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}
// Prevent regular link behavior, which causes a browser refresh.
event.preventDefault();
router.history.push(location);
};
return { href, onClick };
};