John williams
John williams

Reputation: 731

Setting a baseurl in a react router

I am having trouble setting up a router that respects the current URL. So the website isn't a full react build but it initializes the react app on a specific route (http://thesite.com/tv/videos/playlists). Now when I am using the react-router it was changing the URL to https://thesite.com/{reactRoute}.

So i used window.location.pathname

import * as React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
} from 'react-router-dom';
import { createBrowserHistory } from 'history';


import HomeContainer from './containers/HomeContainer';
import PlayListContainer from './containers/PlayListContainer';


const baseUrl = window.location.pathname;
console.log(baseUrl);

const App: React.FC =
  () => {
    const history = createBrowserHistory({ basename: baseUrl });

    return (
      <Router history={history}>
        <div>
          <nav>
            <ul>
              <li>
                <Link to={{pathname: '/'}}>Home</Link>
              </li>
              <li>
                <Link to={`${baseUrl}/playlists`}>Playlist</Link>
              </li>
            </ul>
          </nav>
  
          <Switch>
            <Route path="/">
              <HomeContainer />
            </Route>
            <Route path={`${baseUrl}/playlists`}>
              <PlayListContainer />
            </Route>
          </Switch>
        </div>
      </Router>
    );
  }

export default App;

The issue is now it maintains the base URL and prepends the react route accordingly but going to anything other than the base route doesn't work so clicking on the playlists link doesn't initiate the playlists route.

Any help is much appreciated.

Upvotes: 1

Views: 5372

Answers (1)

mr. D
mr. D

Reputation: 58

If you add <Route exact path="/"> on your home route in the switch statement you should be fine. The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url. This is explained in the docs.

You code could look something like this:

<Router history={history}>
  <div>
    <nav>
      <ul>
        <li>
          <Link to={{ pathname: "/" }}>Home</Link>
        </li>
        <li>
          <Link to="/playlists">Playlist</Link>
        </li>
      </ul>
    </nav>

    <Switch>
      <Route exact path="/">
        <HomeContainer />
      </Route>
      <Route path="/playlists">
        <PlayListContainer />
      </Route>
    </Switch>
  </div>
</Router>

Upvotes: 2

Related Questions