Skip to content

Instantly share code, notes, and snippets.

@ca057
Created May 10, 2021 12:56
Show Gist options
  • Save ca057/1d9c7eed75edc553198f9ed68b6e43bc to your computer and use it in GitHub Desktop.
Save ca057/1d9c7eed75edc553198f9ed68b6e43bc to your computer and use it in GitHub Desktop.
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment