-
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
useLinkProps.tsx
71 lines (64 loc) · 2.3 KB
/
useLinkProps.tsx
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import {
NavigationAction,
NavigationContainerRefContext,
NavigationHelpersContext,
} from '@react-navigation/core';
import * as React from 'react';
import { GestureResponderEvent, Platform } from 'react-native';
import useLinkTo, { To } from './useLinkTo';
type Props<ParamList extends ReactNavigation.RootParamList> = {
to: To<ParamList>;
action?: NavigationAction;
};
/**
* Hook to get props for an anchor tag so it can work with in page navigation.
*
* @param props.to Absolute path to screen (e.g. `/feeds/hot`).
* @param props.action Optional action to use for in-page navigation. By default, the path is parsed to an action based on linking config.
*/
export default function useLinkProps<
ParamList extends ReactNavigation.RootParamList
>({ to, action }: Props<ParamList>) {
const root = React.useContext(NavigationContainerRefContext);
const navigation = React.useContext(NavigationHelpersContext);
const linkTo = useLinkTo<ParamList>();
const onPress = (
e?: React.MouseEvent<HTMLAnchorElement, MouseEvent> | GestureResponderEvent
) => {
let shouldHandle = false;
if (Platform.OS !== 'web' || !e) {
shouldHandle = e ? !e.defaultPrevented : true;
} else if (
!e.defaultPrevented && // onPress prevented default
// @ts-expect-error: these properties exist on web, but not in React Native
!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) && // ignore clicks with modifier keys
// @ts-expect-error: these properties exist on web, but not in React Native
(e.button == null || e.button === 0) && // ignore everything but left clicks
// @ts-expect-error: these properties exist on web, but not in React Native
[undefined, null, '', 'self'].includes(e.currentTarget?.target) // let browser handle "target=_blank" etc.
) {
e.preventDefault();
shouldHandle = true;
}
if (shouldHandle) {
if (action) {
if (navigation) {
navigation.dispatch(action);
} else if (root) {
root.dispatch(action);
} else {
throw new Error(
"Couldn't find a navigation object. Is your component inside NavigationContainer?"
);
}
} else {
linkTo(to);
}
}
};
return {
href: to,
accessibilityRole: 'link' as const,
onPress,
};
}