fix: add ability to pass generic params to Link

This commit is contained in:
Satyajit Sahoo
2021-05-14 09:29:57 +02:00
parent ea8ea20127
commit 9c30c42c0b
3 changed files with 19 additions and 10 deletions

View File

@@ -4,8 +4,8 @@ import type { NavigationAction } from '@react-navigation/core';
import useLinkProps from './useLinkProps';
import type { To } from './useLinkTo';
type Props = {
to: To;
type Props<ParamList extends ReactNavigation.RootParamList> = {
to: To<ParamList>;
action?: NavigationAction;
target?: string;
onPress?: (
@@ -21,8 +21,12 @@ type Props = {
* @param props.action Optional action to use for in-page navigation. By default, the path is parsed to an action based on linking config.
* @param props.children Child elements to render the content.
*/
export default function Link({ to, action, ...rest }: Props) {
const props = useLinkProps({ to, action });
export default function Link<ParamList extends ReactNavigation.RootParamList>({
to,
action,
...rest
}: Props<ParamList>) {
const props = useLinkProps<ParamList>({ to, action });
const onPress = (
e: React.MouseEvent<HTMLAnchorElement, MouseEvent> | GestureResponderEvent

View File

@@ -6,8 +6,8 @@ import {
} from '@react-navigation/core';
import useLinkTo, { To } from './useLinkTo';
type Props = {
to: To;
type Props<ParamList extends ReactNavigation.RootParamList> = {
to: To<ParamList>;
action?: NavigationAction;
};
@@ -17,9 +17,11 @@ type Props = {
* @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({ to, action }: Props) {
export default function useLinkProps<
ParamList extends ReactNavigation.RootParamList
>({ to, action }: Props<ParamList>) {
const navigation = React.useContext(NavigationHelpersContext);
const linkTo = useLinkTo();
const linkTo = useLinkTo<ParamList>();
const onPress = (
e?: React.MouseEvent<HTMLAnchorElement, MouseEvent> | GestureResponderEvent

View File

@@ -21,12 +21,14 @@ export type To<
params: ParamList[RouteName];
});
export default function useLinkTo() {
export default function useLinkTo<
ParamList extends ReactNavigation.RootParamList
>() {
const navigation = React.useContext(NavigationContext);
const linking = React.useContext(LinkingContext);
const linkTo = React.useCallback(
(to: To) => {
(to: To<ParamList>) => {
if (navigation === undefined) {
throw new Error(
"Couldn't find a navigation object. Is your component inside a screen in a navigator?"
@@ -42,6 +44,7 @@ export default function useLinkTo() {
}
if (typeof to !== 'string') {
// @ts-expect-error: This is fine
root.navigate(to.screen, to.params);
return;
}