#Setting the location for a static router with React Router v6

1 messages · Page 1 of 1 (latest)

slim carbon
#

So previously the way to set the location on <StaticRouter /> is by manipulating its location prop. React Router v6 still supports this as shown in the docs here:
https://reactrouter.com/en/main/router-components/static-router

However, now it seems like the new recommended way is to create a static router using createStaticRouter as shown in the docs here:
https://reactrouter.com/en/main/routers/create-static-router

Is there a way to set the location when using a static router created with createStaticRouter?


To elaborate as to why I'm running into this issue: I'm currently server-side rendering and originally I was using BrowserRouter for my frontend router and a corresponding StaticRouter for the backend's server-side render.

I currently implement my error pages with the errorElement prop but I realized that error pages won't render and any thrown error will crash my apps because the prop requires usage within a data router to work. More on this issue is discussed in here:
https://github.com/remix-run/react-router/issues/10021

I did switch to using createBrowserRouter on my frontend and my error pages work there, but when I server-side render the server crashes because my Express server still relies on the location prop for <StaticRouter /> and I can't find a way to get the equivalent functionality with createStaticRouter.

slim carbon
#

Setting the location for a static router with React Router v6

mild valley
#

In v6, RouterProvider/StaticRouterProvider are "data routers" and sort of operate on the assumption that you're using loaders and actions and the other new Data APIs. On the server this means that there's a bit of an assumption that you're fetching data and then rendering StaticRouterProvider

#

So with the current API the location is part of the request you give to the static handler, and then it is encoded in the context you get back and pass to
StaticRouterProvider

#
let { query, dataRoutes } = createStaticHandler(routes);
let context = await query(new Request(url));
//       SSR Location comes from here ^  
...
let router = createStaticRouter(dataRoutes, context);
return ReactDOMServer.renderToString(
  <StaticRouterProvider router={router} context={context} />
);
#

Even if your routes don't use loaders, you'll still use that pattern because query also does route macthing and return the routes that StaticRouterProvider should render