Last active
September 21, 2020 11:54
-
-
Save maraisr/9e1c15d7226da872c426ef458759d4ad to your computer and use it in GitHub Desktop.
EntrypointContainer w/ react-router
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 type { ElementType } from 'react'; | |
import * as React from 'react'; | |
import { useMemo } from 'react'; | |
import { EntryPointContainer, loadEntryPoint } from 'react-relay/hooks'; | |
import type { EntryPoint } from 'react-relay/lib/relay-experimental/EntryPointTypes'; | |
import { matchPath, useResolvedPath } from 'react-router'; | |
import { resolvePath, useLocation } from 'react-router-dom'; | |
import repositoryEntrypoint from './Repository.entrypoint'; | |
interface RouteConfig<Params extends {} = {}, Component extends ElementType = any> { | |
path: string; | |
entryPoint: EntryPoint<Params, Component> | |
} | |
const routes: RouteConfig[] = [ | |
{ path: '.', entryPoint: repositoryEntrypoint }, | |
]; | |
const useEntrypointRouter = (routes: RouteConfig[]) => { | |
const location = useLocation(); | |
const currentPath = useResolvedPath('.'); | |
return routes.find(route => matchPath(resolvePath(route.path, currentPath.pathname).pathname, location.pathname))?.entryPoint ?? undefined; | |
}; | |
const App = () => { | |
const currentEntrypointReference = useEntrypointRouter(routes); | |
const entryPoint = useMemo(() => loadEntryPoint( | |
environmentProvider, | |
currentEntrypointReference, | |
), [currentEntrypointReference]); | |
return <Router> | |
{currentEntrypointReference ? <EntryPointContainer | |
entryPointReference={entryPoint} | |
props={{}} | |
/> : null} | |
</Router>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment