How to use react-i18next with createBrowserRourter in React Router v6.22.2?

64 views Asked by At

I'm wondering if anybody has used the react-i18next library with the latest React Router v6 and the createBrowserRouter().

I'm experiencing the following warning in my web application: i18next warning

In React Router v6 the suggested router is createBrowserRouter() which needs to know all the routes ahead of time. My file structure has the routes in the index.ts of each page's directory and in that index.ts file I'm defining some meta data about the page.

The meta data is a const and includes the name of the page which is wrapped in i18n.t() which is causing warnings about using the function before the library has been initialized. I'm wondering if there are any best practices that should be followed in scenarios like this.

I'm hoping somebody has done this before or can maybe point me in the right direction?

The pseudo file structure/code looks like similar to this (I didn't define all the objects properly):

main.tsx

import routes from 'routes.ts'

const router = createBrowserRouter([
  ...router config and routes
])

ReactDOM.createRoot(document.getElementById('root'!).render(
  <RouteProvider router=router/>
))

routes.ts

import routes1 from '.page1'
import routes2 from '.page2'

const routes = [
  routes1,
  routes2,
  ...
]

export default routes;

page1/index.ts

const metaData = {
  title: i18n.t('Page Title')
  ...
}

const routes = [
  {route with meta Data}
  ...
]

export default routes;
  1. I've considered changing the const metadata = [...] to a function like getPageData(i18n).
  2. I've considered changing the routes so each page has a getRoutes() function that is executed after i18n has been initialized. And then I would call getAllRoute() in the main.ts where createBrowserRouter() is defined.

Edit: Here is a CodeSandbox minimal reproducible example as requested. If you inspect developer tools you will see the issue warning from above.

Edit: I think I found a solution

Edit: Here's an example route that's more descriptive

const routes: RouteObject[] = [{
  path: "/example",
  handle: {
    // I'm not sure how to use the translate function properly below
    text: t("Example Page"),
    crumb: (data: object) => ({ ...data, text: t("Example Page") }),
  },
  element: <ExamplePage />,
  ...
}]

export default routes;

TLDR: I have strings in the handle key of my RouteObjects[] that need to use the react-i18next translate function but I'm not sure the correct way to wait for the react-i18n to finish initializing before using it.

0

There are 0 answers