I'm using i18-next library to switch languages in my app. So it's done without reloading a page. The language switch is done via:
render() {
const toggle = lng => i18n.changeLanguage(lng);
return (
<a href="javascript:void(0)" onClick={()=>{ toggle();}}></a>
)
I'd make such functionality: once the language is switched add to a URL a language param. So once change is occured it should looks like: www.website.com/xx
I've read mostly all topics regarding Rect-Router v4 and history but all suggestions didn't work in my project. Some of them are related to obsolete functionality. I've also tried few example with withRouter, but nothing worked...
How it could be achieved in my case?
index.js:
import { Router, Route, Switch } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
const customHistory = createBrowserHistory();
...
return (
<I18nextProvider i18n={i18n}>
<div>
<Router history={customHistory}>
<Switch>
<Route exact path="/:lng?" component={Page} />
<Route path={`/:lng?/someURL`} component={Page}/>
...
<Route component={NoMatch} />
</Switch>
</Router>
<ModalContainer />
</div>
</I18nextProvider>
)
navigation component:
handleClick() {
**append URL with lang param**
console.log(history);
-> history: History { length: 1, scrollRestoration: "auto", state: null }
history.push('/redirected');
-> TypeError: history.push is not a function
}
render() {
const toggle = lng => i18n.changeLanguage(lng);
return (
<a href="javascript:void(0)" onClick={()=>{ toggle(this.props.event); this.handleClick(); }}></a>
)
Should it be done with function as handleClick() or this event should be global? The languages are switched from several components.
React-Router V4.2.0