Search code examples
javascriptreactjsreduxreact-reduxflux

Setting default language on react js (redux)


I'm trying to make a default 'en' language for my react redux app, for now I insert the language in the store, but I want to use the en.json file in my lang folder and then make a switch between languages.

ConfigStore.js

import { ReduceStore } from 'flux/utils';
import ActionTypes from '../constants/AppConstants';
import AppDispatcher from '../dispatcher/AppDispatcher';
import config from '../../config';


class ConfigStore extends ReduceStore {

    getInitialState() {
        return {
            language: 'en',
            languageLabels: {}
        };
    }

    reduce(state, action) {
        switch (action.type) {
            case ActionTypes.LANGUAGE_REQUEST:
                var newState = Object.assign({}, state);
                newState.languageLabels = action.data;
                return newState;
            default:
                return state;
        }
    }
}

export default new ConfigStore(AppDispatcher);

App.js

    import React from "react";
    import { render } from "react-dom";
    import { BrowserRouter as Router, Route } from "react-router-dom";
    import Main from "./components/Main";
    import ErrorBoundary from "./components/ErrorBoundary";

    render(
        <Router>
            <ErrorBoundary>
                <div>
                    <Route path="/" component={ Main }/>
                </div>
            </ErrorBoundary>
        </Router>,
        document.getElementById("root")
    );

config.js

this is the file where I have the default settings

const config = {
ServiceConfig: {
    url: 'http://192.168.30.145',
    port: '4000',
    ip: '127.0.0.1'
},

AppConfig: {
    appID: 'wsTrader',
    appName: 42,
    isManager: 0,
    key: '!@#TempKey',
    phoneLine: '0'
},

SiteConfig: {
    defaultLanguage: 'en'
}
};

module.exports = config;

Solution

  • You can use a package called helmet to handle this:

    import { Helmet } from 'react-helmet';
    

    Then in your render method, you can have something like this:

    class Application extends React.Component {
      render () {
        return (
            <div className="application">
                <Helmet htmlAttributes={{ lang: some.language.from.redux.store }}>
                    <meta charSet="utf-8" />
                    <title>My Title</title>
                </Helmet>
                ...
            </div>
        );
      }
    };