@react-navigation/native
Version:
React Native integration for React Navigation
90 lines (87 loc) • 3.22 kB
JavaScript
;
import { getPathFromState, NavigationContainerRefContext, NavigationHelpersContext } from '@react-navigation/core';
import * as React from 'react';
import { Platform } from 'react-native';
import { LinkingContext } from "./LinkingContext.js";
const getStateFromParams = params => {
if (params?.state) {
return params.state;
}
if (params?.screen) {
return {
routes: [{
name: params.screen,
params: params.params,
// @ts-expect-error this is fine 🔥
state: params.screen ? getStateFromParams(params.params) : undefined
}]
};
}
return undefined;
};
/**
* Hook to get props for an anchor tag so it can work with in page navigation.
*
* @param props.screen Name of the screen to navigate to (e.g. `'Feeds'`).
* @param props.params Params to pass to the screen to navigate to (e.g. `{ sort: 'hot' }`).
* @param props.href Optional absolute path to use for the href (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 function useLinkProps({
screen,
params,
href,
action
}) {
const root = React.useContext(NavigationContainerRefContext);
const navigation = React.useContext(NavigationHelpersContext);
const {
options
} = React.useContext(LinkingContext);
const onPress = e => {
// @ts-expect-error: these properties exist on web, but not in React Native
const hasModifierKey = 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
const isLeftClick = e.button == null || e.button === 0; // only handle left clicks
const isSelfTarget = [undefined, null, '', 'self'].includes(
// @ts-expect-error: these properties exist on web, but not in React Native
e.currentTarget?.target); // let browser handle "target=_blank" etc.
let shouldHandle = false;
if (Platform.OS !== 'web' || !e) {
shouldHandle = true;
} else if (!hasModifierKey && isLeftClick && isSelfTarget) {
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 {
// @ts-expect-error This is already type-checked by the prop types
navigation?.navigate(screen, params);
}
}
};
const getPathFromStateHelper = options?.getPathFromState ?? getPathFromState;
return {
href: href ?? (Platform.OS === 'web' && screen != null ? getPathFromStateHelper({
routes: [{
// @ts-expect-error this is fine 🔥
name: screen,
// @ts-expect-error this is fine 🔥
params: params,
// @ts-expect-error this is fine 🔥
state: getStateFromParams(params)
}]
}, options?.config) : undefined),
accessibilityRole: 'link',
onPress
};
}
//# sourceMappingURL=useLinkProps.js.map