Created
August 20, 2022 18:42
-
-
Save AshMW2724/37657dc3a5136bf1fbc824c4a117e6d4 to your computer and use it in GitHub Desktop.
takes catch-all route's slug and returns components based on what that route is.
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 { createContext, ReactElement, ReactNode, useContext } from 'react'; | |
const SlugContext = createContext<{ slug: string[]; parsedSlug: string }>({ slug: [], parsedSlug: '/' }); | |
const SlugRouteContext = createContext({ route: '/' }); | |
interface SlugProps { | |
children: ReactElement<SlugRouteProps>[] | ReactElement<SlugRouteProps>; | |
slug: string[]; | |
} | |
interface SlugRouteProps { | |
children: ReactNode; | |
route: `/${string}`; | |
strict?: boolean; | |
} | |
function Slug(props: SlugProps) { | |
const { children, slug } = props; | |
const parsedSlug = `/${slug.join('/')}`; | |
return <SlugContext.Provider value={{ slug, parsedSlug }}>{children}</SlugContext.Provider>; | |
} | |
function SlugRoute(props: SlugRouteProps) { | |
const { children, route, strict } = props; | |
const { parsedSlug } = useContext(SlugContext); | |
const { route: parentRoute } = useContext(SlugRouteContext); | |
const parsedRoute = parentRoute === '/' ? route : parentRoute + route; | |
if (strict ? parsedSlug !== parsedRoute : !parsedSlug.startsWith(parsedRoute)) return null; | |
return <SlugRouteContext.Provider value={{ route: parsedRoute }}>{children}</SlugRouteContext.Provider>; | |
} | |
Slug.Route = SlugRoute; | |
export default Slug; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment