Created
March 23, 2020 13:27
-
-
Save srph/95aef11a6155ee60979a975f91dae580 to your computer and use it in GitHub Desktop.
React: Unfinished 1-level deep navigation stack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useContext, useState, useEffect } from 'react' | |
interface NavigationItem { | |
back: string | |
title: string | |
} | |
interface ContextType { | |
active: NavigationItem | null | |
setActive: (active: NavigationItem | null) => void | |
} | |
const Context = React.createContext<ContextType>({ | |
active: null, | |
setActive: () => {} | |
}) | |
/** | |
* Provides a 1-level deep stack for the NavigationBar to show either a normal navigation bar or a back button | |
*/ | |
export function NavigationProvider({ children }: { children: React.ReactNode }) { | |
const [active, setActive] = useState<NavigationItem | null>(null) | |
return <Context.Provider value={{ active, setActive }}>{children}</Context.Provider> | |
} | |
/** | |
* Used by the navigation bar to access state | |
*/ | |
export function useNavigation() { | |
return useContext(Context) | |
} | |
/** | |
* Used by actual screens to update title and state | |
*/ | |
export function useNavigationStack(item: NavigationItem): void { | |
const context = useNavigation() | |
useEffect(() => { | |
context.setActive(item) | |
return () => { | |
context.setActive(null) | |
} | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment