Skip to content

Instantly share code, notes, and snippets.

@maticzav
Created April 16, 2020 15:14
Show Gist options
  • Save maticzav/793de24b2f946fad863dcd2ede1e16e4 to your computer and use it in GitHub Desktop.
Save maticzav/793de24b2f946fad863dcd2ede1e16e4 to your computer and use it in GitHub Desktop.
import * as React from 'react'
import { NavigationContext, NavigationProp } from '@react-navigation/native'
import { ParamListBase } from '@react-navigation/routers'
/* Registry */
export type Route =
| { name: 'feed' }
| { name: 'meal'; id: string }
| { name: 'login' }
function routeToScreen(route: Route): [string, object] {
const name = route.name
switch (name) {
case 'feed': {
return ['Feed', {}]
}
case 'meal': {
return ['Meal', {}]
}
case 'login': {
return ['Login', {}]
}
default: {
const never: never = name
throw new Error(`Unimplemented path ${name}`)
}
}
}
/* Behind the scenes */
type StoryNavigationProp = NavigationProp<ParamListBase> & {
goto: (route: Route) => () => void
}
/**
* Provides the story methods to function.
*/
export function useStory<T extends StoryNavigationProp>(): T {
const navigation = React.useContext(NavigationContext) as StoryNavigationProp
if (navigation === undefined) {
throw new Error("Couldn't find a navigation object.")
}
/* append goto method */
navigation.goto = (route: Route) => () =>
navigation.navigate(...routeToScreen(route))
return navigation as T
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment