I am building an multilingual application with React & Redux using :
{
"react": "16.2.0",
"redux": "3.7.2",
"react-redux": "^5.0.6",
"react-router-redux": "^5.0.0-alpha.9",
"react-router": "^4.2.0",
"react-redux-i18n": "^1.9.1"
}
SOLVED (using path-to-regexp
) : https://codesandbox.io/s/307nz4p9nm
EDIT : Finally able to render components. Last trouble is the path generation, for my language selectors.
I am using a <ConnectedRouter />
relying on createBrowserHistory()
.
I have the following structure :
// containers/App.jsx
<div>
<ul>
<li>
<NavLink to={`${match.url}/`}>Home</NavLink>
</li>
<li>
<NavLink to={`${match.url}/ABC`}>ABC</NavLink>
</li>
<li>
<NavLink to={`${match.url}/DEF`}>DEF</NavLink>
</li>
<li>
<NavLink to={`${match.url}/GHI`}>GHI</NavLink>
</li>
<li>
<NavLink to={`${match.url}/JKL`}>JKL</NavLink>
</li>
</ul>
<div>
<Router />
</div>
<footer>
<Link to={ (???) }>English</Link>
<Link to={ (???) }>French</Link>
</footer>
</div>
// containers/Router.jsx
<Switch>
<Route exact path={`{match.url}/`} component={Home} />
<Route exact path={`{match.url}/abc`} component={AbcComponent} />
<Route exact path={`{match.url}/def`} component={DefComponent} />
<Route exact path={`{match.url}/ghi`} component={GhiComponent} />
<Route exact path={`{match.url}/jkl`} component={JklComponent} />
</Switch>
// containers/RootContainer.jsx
<Provider store={store}>
<ConnectedRouter history={history}>
<Switch>
<Route path='/:locale(en|fr)' component={App} />
<Redirect to='/en' />
</Switch>
</ConnectedRouter>
</Provider>
Rendered this way :
const store = createStore(combineReducers({}))
const history = createBrowserHistory()
ReactDOM.render(
<RootContainer store={store} history={history} />,
document.getElementById('app-container')
)
Which result in the following URIs :
/
/(en|fr)
/abc
/def
/ghi
/jkl
Now, I am looking for a way to implement my locale selectors : generate the path of the current page, just updating the :locale
parameter.
Whatever is the route I am currently visiting (/en
, /en/abc
), match.path
always return /:locale(en|fr)
and I never access the sub-path (eg. /abc
) from my App component.
Then how to hook react-redux-i18n
to automatically take the locale from URL instead of managing it in its own state ?
<Switch>
only works with Route and Redirect as direct descendents. So the LocalizedRoute
component does not work.
<ConnectedRouter basename=/:locale/ history={history} />
The basename prop is unknown to me and unnecessary imo, remove it.
What you can do is using a dynamic route:
<Route path="/:locale/<path>"/>
And reduce on the locale param in the LOCATION_CHANGE
action. But there are plenty more solutions, something like:
<Switch>
<Route path="/en" component={SwitchMyRoutes} /> // No exact!!
<Route path="/fr" render={(match,location)=> <SwitchMyRoutes locale="fr" match={match}/>} />
<Route render={({location})=> <Redirect to={`/en/${location}`}/>}/>
</Switch>