Search code examples
reactjstypescriptreact-routerreact-redux-form

React Router root element with param


I am rewriting an ASP.NET MVC app to use React with Redux in TypeScript. For routing I am using React Router. The site uses a parameter at to the root to identify the customer's organization.

Example; www.oursite.com/:organizationId with deep links like www.oursite.com/:organizationId/overview or www.oursite.com/:organizationId/account/:accountId

I have configured React router as below

import * as React from 'react';
import { Router, Route, IndexRoute, HistoryBase } from 'react-router';
import { Layout } from './components/Layout';
import Home from './components/Home';
import OverView from './components/OverView';
import Account from './components/Account';

export default <Route path='/:organizationId' component={ Layout }>
    <IndexRoute components={{ body: Home }} />
    <Route path='overview' components={{ body: OverView }} />
    <Route path='account/:accountId' components={{ body: Account }} />
</Route>;

This works, but any Link components on pages do not, as the root of the app/page is still /.

For example

<Link to={'/overview'} activeClassName='active' />

on the Account control links to www.oursite.com/overview, not www.oursite.com/:organizationId/overview.

Is there a way to configure the React Router to consider /:organizationId/ as the root?


Solution

  • If you take a look at the react router docs it looks like relative links as strings are not supported by react-router. Currently only absolute links are supported.

    https://github.com/ReactTraining/react-router/blob/master/docs/API.md#link

    However, I think what you are looking for is params. React-router passes down params as props to every component that is connected to a route. For example in your overview component there should params prop. You should be able to do something like

    <Link to={`/${this.props.params.organizationId}/overview`></Link>

    Let me know if this helps!