Redirect back to default language i18n

Viewed 494

How can I set the default language in i18n? The problem is when the user inserts none existing language in the path, the page is disappearing. The defined languages are => en, es, ar. I want to set the default language to "EN", when the user inserts in the path for example "ru" the user redirects back to English.

Here is the code for i18n.js

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';

const languages = ["en", "es", "ar"]
const options = {
    loadPath: "./public/locales/{{lng}}/{{translation}}.json",
}

i18n
    .use(Backend)
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
        fallbackLng: "en",
        debug: true,
        // lng: "en",
        whitelist: ["en", "es", "ar"],
        keySeparator: false,
        checkWhitelist: true,
        detection: {
            order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'],  
            lookupFromPathIndex: 0,
            caches: ['cookie'],
            checkWhitelist: true,
        },  
    });
export default i18n;

Please take into consideration that LNG can't be defined here. When I use lng the translations are not working.

File: Route.js

export const baseUrl = () => {
    return (
        i18n.language === 'en' ? '' : '/' + i18n.language
    )
};

const Router = () => {
    const baseRouteUrl = "/:locale(es|en|ar)?";
    return (
        <Switch>
            <Route exact path="/" component={Options} />
            <Route exact path="/login" component={Login} />
            <Route exact path="/register" component={Register} />

            <PrivateRoute exact path={baseRouteUrl + "/dashboard"}
                    render={(props) => {
                        return (
                            <MainLayout>
                                <DashboardPage />
                            </MainLayout>
                        )
                    }}
                />

File: Menu.jsx

<Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
     <Menu.Item key="1" active icon={<HomeOutlined />}>
      {
           <Link to={baseUrl() + "/dashboard"}>
               {t("DASHBOARD")}
           </Link>
       }
     </Menu.Item>

1 Answers

You can write is a Route with regex path at the end of all the routes to catch all and redirect.

<Route
  path="/:lang([A-Za-z]{2})?/:rest*"
  render={props => {
    // availabeLanguages is an array of language codes
    if (!availableLanguages.includes(props.match.params.lang)) {
      // depending on your configuration you may need 
      // to set the language to your default language before return
      return (<Redirect to={`/${props.match.params.rest}`}/>);
    }
  }}/>
Related