Skip to content

Instantly share code, notes, and snippets.

@ca057
Created May 10, 2021 12:56
  • Select an option

Select an option

Revisions

  1. ca057 created this gist May 10, 2021.
    28 changes: 28 additions & 0 deletions withNavigationParamsHoc.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    import React from 'react';
    import { NavigationStackScreenProps } from 'react-navigation-stack';

    interface Props extends NavigationStackScreenProps {
    foo: string;
    }
    const TestScreen = ({ navigation, foo }: Props) => {
    const barDirectly = navigation.getParam('bar');

    return <Text>bar from navigation: {barDirectly} bar as foo from HOC: {foo}</Text>;
    };

    const withNavigationParam = <P extends NavigationStackScreenProps>(
    mapPropsToParams: { [key in keyof P]?: P[key] },
    ) => (Component: React.ComponentType<P>) => (props: P) => {
    const propsFromParams = Object.entries(mapPropsToParams).reduce(
    (finalProps, [propName, paramName]) => ({
    ...finalProps,
    [propName]: props.navigation.getParam(paramName),
    }),
    {},
    );
    return <Component {...propsFromParams} {...props} />;
    };

    export default withNavigationParam<Props>({
    foo: 'bar',
    })(TestScreen);