UNPKG

2.11 kBJavaScriptView Raw
1import * as React from 'react';
2import { Platform } from 'react-native';
3import { NavigationHelpersContext } from '@react-navigation/core';
4import useLinkTo from './useLinkTo';
5
6/**
7 * Hook to get props for an anchor tag so it can work with in page navigation.
8 *
9 * @param props.to Absolute path to screen (e.g. `/feeds/hot`).
10 * @param props.action Optional action to use for in-page navigation. By default, the path is parsed to an action based on linking config.
11 */
12export default function useLinkProps({
13 to,
14 action
15}) {
16 const navigation = React.useContext(NavigationHelpersContext);
17 const linkTo = useLinkTo();
18
19 const onPress = e => {
20 var _e$currentTarget;
21
22 let shouldHandle = false;
23
24 if (Platform.OS !== 'web' || !e) {
25 shouldHandle = e ? !e.defaultPrevented : true;
26 } else if (!e.defaultPrevented && // onPress prevented default
27 // @ts-expect-error: these properties exist on web, but not in React Native
28 !(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) && ( // ignore clicks with modifier keys
29 // @ts-expect-error: these properties exist on web, but not in React Native
30 e.button == null || e.button === 0) && // ignore everything but left clicks
31 // @ts-expect-error: these properties exist on web, but not in React Native
32 [undefined, null, '', 'self'].includes((_e$currentTarget = e.currentTarget) === null || _e$currentTarget === void 0 ? void 0 : _e$currentTarget.target) // let browser handle "target=_blank" etc.
33 ) {
34 e.preventDefault();
35 shouldHandle = true;
36 }
37
38 if (shouldHandle) {
39 if (action) {
40 if (navigation) {
41 navigation.dispatch(action);
42 } else {
43 throw new Error("Couldn't find a navigation object.");
44 }
45 } else {
46 if (typeof to !== 'string') {
47 throw new Error("To 'to' option is invalid (found '".concat(String(to), "'. It must be a valid string for navigation."));
48 }
49
50 linkTo(to);
51 }
52 }
53 };
54
55 return {
56 href: to,
57 accessibilityRole: 'link',
58 onPress
59 };
60}
61//# sourceMappingURL=useLinkProps.js.map
\No newline at end of file