My application has more than one locale (it, en).
I need to translate all the routes. For example I have the terms and condition page that has to paths (one per locale):
it/termini
en/terms
I need than to do something like:
// routes.js
const routes = (
<Route path="/" ponent={App}>
<IndexRoute ponent={HomePage} />
<Route path="(it/termini)(en/terms)" ponent={TermsPage} />
<Route path="*" ponent={NotFoundPage} />
</Route>
)
As you can see this funky solution is not so good for the scalability of the application.
My application has more than one locale (it, en).
I need to translate all the routes. For example I have the terms and condition page that has to paths (one per locale):
it/termini
en/terms
I need than to do something like:
// routes.js
const routes = (
<Route path="/" ponent={App}>
<IndexRoute ponent={HomePage} />
<Route path="(it/termini)(en/terms)" ponent={TermsPage} />
<Route path="*" ponent={NotFoundPage} />
</Route>
)
As you can see this funky solution is not so good for the scalability of the application.
Share Improve this question edited Aug 22, 2016 at 13:09 cl0udw4lk3r asked Aug 22, 2016 at 12:53 cl0udw4lk3rcl0udw4lk3r 2,7336 gold badges28 silver badges46 bronze badges1 Answer
Reset to default 6My current approach with routes localization is to deal with them as I do with any localized content. In your case I would do:
// routes.js
function createRoutes(language) {
/*
You'll probably have more work to do here,
such as sub-routes initialization
ponent's type selection logic, etc.
@note: _t(key, language) is your
translation function
*/
return (
<Route
key={language}
path={_t("it/termini", language)}
ponent={TermsPage}
/>
)
}
let localizedRoutes = supportedLanguages.map(createRoutes)
const routes = (
<Route path="/" ponent={App}>
<IndexRoute ponent={HomePage} />
{localizedRoutes}
<Route path="*" ponent={NotFoundPage} />
</Route>
)
Then you can specify them in your translation files just as any other string, including any parameter:
// en.js
module.exports = {
//...
"it/termini" : "en/terms",
"it/profilo/:userId" : "en/profile/:userId"
//...
}
You can also assemble them on the fly before your routes are defined, associating them to the corresponding translation key.
In this way it/termini bees just the key of your translated URL, you could also use something not resembling the underlying URL like terms-page-url.
This method also allows you to differentiate route ponents and/or sub routes per language, which is an added bonus. Just implement the logic inside your mapping function (or where it's appropriate for your application).