Almaron
Almaron

Reputation: 4147

Multilang routes with React Router V4 and redirects

So I have a React app which is using Redux and I need to set up I18n on it. I decided to use the react-redux-i18n package (not sure that's the best idea, but the alternatives like yahoo's react-intl or even react-intl-redux seem to be way too complicated). The initial setup went smoothly, but now I got into a roadblock.

I want to pass the locale as a part of the requested URL. E.g. /en/ for root path, /en/forums for forums, etc. Which means that for every path I need 3 routes:

Writing 3 routes for every path seems way too dirty and uncomfortable so I decided to make a reusable component for it:

import React from 'react';
import { Redirect } from 'react-router-dom';
import LayoutRoute from './LayoutRoute';
import appConfig from './config/appConfig';

class I18nRoute extends React.Component {
    render() {
        const { path, ...rest } = this.props;
        return (
            <div>
                <Redirect from={path} to={`/${appConfig.DEFAULT_LOCALE}${path}`}/>
                <LayoutRoute exact path={`/en?${path}`} lang='en' {...rest} />
                <LayoutRoute exact path={`/ru?${path}`} lang='ru' {...rest} />
            </div>
        )
    }
};

export default I18nRoute;

and then tried using it in my router setup

<Switch>
                <I18nRoute exact path="/" layout={MainLayout} component={Home} />
                <I18nRoute exact path="/forums" layout={MainLayout} component={ForumsRoot} />
                <I18nRoute exact path="/forums/:id" layout={MainLayout} component={Forum} />
                <I18nRoute exact path="/topics/:id" layout={MainLayout} component={Topic} />
                <I18nRoute exact path="/users/:id" layout={MainLayout} component={UsersPage} />
</Switch>

That backfired in two ways:

  1. It doesn't recognize the locale paths, even /en/ leads to route not found.
  2. It doesn't redirect with params in, e.g. /forums/18 gets patched to /en/forums/:id.

is there some fix to this or do I need to go a completely different route? (pun intended)

UPD After carefully writing this down I realized that the redirect rule could be simplified to a regex (if the route does not match /^/(en|ru)/(.*)$/ then redirect to the /en/:path).

Upvotes: 3

Views: 729

Answers (0)

Related Questions