Skip to content

Instantly share code, notes, and snippets.

@AshMW2724
Created August 20, 2022 18:42
Show Gist options
  • Save AshMW2724/37657dc3a5136bf1fbc824c4a117e6d4 to your computer and use it in GitHub Desktop.
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.
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