Skip to content

Instantly share code, notes, and snippets.

@bigfarts
Last active January 17, 2023 17:46
Show Gist options
  • Save bigfarts/b8c4f850444e8be84924d68f01d7949a to your computer and use it in GitHub Desktop.
Save bigfarts/b8c4f850444e8be84924d68f01d7949a to your computer and use it in GitHub Desktop.
import { useEffect, useMemo, useState, useTransition } from "react";
import {
Navigator, Router, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext
} from "react-router-dom";
import { Router as RemixRouter, StaticHandlerContext } from "@remix-run/router";
export default function RouterProvider({
router,
staticContext = undefined,
loadingIndicator = null,
}: {
router: RemixRouter;
staticContext?: StaticHandlerContext;
loadingIndicator?: React.ReactNode;
}) {
const [isPending, startTransition] = useTransition();
const [state, setState] = useState(router.state);
const navigator = useMemo(
(): Navigator => ({
createHref: router.createHref,
encodeLocation: router.encodeLocation,
go: (n) => router.navigate(n),
push: (to, state, opts) =>
router.navigate(to, {
state,
preventScrollReset: opts?.preventScrollReset,
}),
replace: (to, state, opts) =>
router.navigate(to, {
replace: true,
state,
preventScrollReset: opts?.preventScrollReset,
}),
}),
[router]
);
useEffect(() => {
router.subscribe((state) => {
startTransition(() => {
setState(state);
});
});
}, [router]);
return (
<>
{isPending ? loadingIndicator : null}
<UNSAFE_DataRouterContext.Provider
value={{
router,
navigator,
static: staticContext != null,
staticContext,
basename: router.basename || "",
}}
>
<UNSAFE_DataRouterStateContext.Provider value={state}>
<Router
basename={router.basename}
location={state.location}
navigationType={state.historyAction}
navigator={navigator}
>
{state.initialized ? <Routes /> : null}
</Router>
</UNSAFE_DataRouterStateContext.Provider>
</UNSAFE_DataRouterContext.Provider>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment