Search code examples
reactjsreact-localization

Getting URL parameter in index.js in React


I am attempting to get a URL Param to set the correct locales for the whole app, using React.

I have been using queryString.parse(this.props.location.search) without problems inside the components, but it doesn't seem to work in the index.js.

Considering the following code, and that I want to set the locales only once for all the app, how could I read the URL params from the index.js?

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route } from "react-router-dom";

import queryString from 'query-string'

import Register from './components/Register/Register.js';
import Verify from './components/Verify/Verify.js';
import MFA from './components/MFA/MFA.js';

import {IntlProvider} from 'react-intl';
import German from './lang/de.json';
import English from './lang/en.json';


window.LOG_LEVEL = 'DEBUG';

const values = queryString.parse(this.props.location.search)
console.log(values.locales)
const locale = values.locales;

let lang;
if (locale==="en") {
   lang = English;
} else if (locale==="de") {
   lang = German;
}

const App = () => (
    <IntlProvider locale ={locale} messages={lang}>
        <BrowserRouter>
            <div className="h-100">
                <Route path="/" component={Register} exact={true} />
                <Route path="/mfa" component={MFA} />
                <Route path="/verify" component={Verify} />
            </div>
        </BrowserRouter>
    </IntlProvider>
);

const rootElement = document.getElementById("root");
ReactDOM.render( <App />, rootElement);

With the above code I get a Cannot read property 'location' of undefined from the const values = queryString.parse(this.props.location.search)


Solution

  • Try using:

    const values = queryString.parse(window.location.search)