Architecture example for a multi-language application using React, React Redux or React Context, and Material UI

Viewed 1267

I am working in an application with React and Material UI. The application requires to translate the user interface according to locale values. I need to provide facilities for 5 languages. I would like to achieve a similar level of responsiveness like the Material UI documentation page.

I noticed that for the base language, which is English, the routes do not include a language segment on the URL path, but when a language other than English is selected, the URL has a language segment. For example, the Localization page URL in English is https://material-ui.com/guides/localization/ and the same page in French is https://material-ui.com/fr/guides/localization/.

Any references to architecture patterns or example code would be appreciated.

4 Answers

What are the good things about it

  • In the future if you need to change the path name you can just change PATHS
  • You can add the component in a config file genericRoutes
  • for localization path={`/:language?/${path}`} you can use like this.
import { Route } from 'react-router-dom';

const PATHS = {
    SIGN_UP: '/sign-up',
    CONFIRMATION: '/confirmation'
}

const genericRoutes = [
    {
      path: PATHS.SIGN_UP,
      component: SignUp,
    },
    {
      path: PATHS.CONFIRMATION,
      component: Confirmation,
    },
]

const GenericRoute = (props) => <Route {...props} />;

const Routes = () => {
    return (
        <Switch>
            {genericRoutes.map(({ path, component, exact = true }, key) => (
                <GenericRoute
                key={key}
                exact={exact}
                path={`/:language?/${path}`}
                component={component}
                />
            ))}
        </Switch>
    )
}


It's not quite what you are looking for but might I also suggest you give i18next a look? It gives you a lot of flexibility when choosing the display language and can even detect the user's browser's language. You also have the option to pass the language in the path, similar to what others have suggested. Configuring it is straightforward, you can interpolate values, have a fallback language, just to name a few of the features it offers.

P.S. Here is how Material UI do it if you are striving for the same thing.

It seems you are looking for a route like this one:

<Route path="/:language?/guides/localization">
  {props => <div>{Object.entries(props.match.params).map(p => `${p[0]}=${p[1]}`).join(" ")}</div> }
</Route>

If props.match.params.language is undefined, just use the default value (i.e. English).

In my current project, I am using i18next as a hook, it comes up with the hook name useTranslation. In the above link, I have attached the step by step guide to do the same. With the help of this, we are supporting the translation of 28 languages and it is working amazingly for us.

I hope it will help you as well. :)

Related