Skip to content

Instantly share code, notes, and snippets.

@srph
Created March 23, 2020 13:27
Show Gist options
  • Save srph/95aef11a6155ee60979a975f91dae580 to your computer and use it in GitHub Desktop.
Save srph/95aef11a6155ee60979a975f91dae580 to your computer and use it in GitHub Desktop.
React: Unfinished 1-level deep navigation stack
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