gibsonsp
gibsonsp

Reputation: 93

How to set relative paths using React Router in an existing ASP.NET Core app that is using MVC

First off, I would like to know if my course of action seems reasonable.

I am trying to integrate React within a large ASP.NET Core project. This project is a traditional MVC application. I have been tasked with adding the functionality to incorporate React for a settings page.

The page consists of 4 other settings pages. I was thinking this would be a good opportunity to incorporate client-side rendering in order to route to each settings pages.

The setup is like this.

  1. Once the application starts, the path looks like this: https://localhost:3000/

  2. Navigating to settings looks like this: https://localhost:3000/settings

  3. I want to be able to go further and route like this: https://localhost:3000/settings/permissions

But I don't want to hard code the route "https://localhost:3000/settings/". The problem is that the application is utilizing a traditional MVC, and the way that the user actually navigates to the settings page is totally separate from the page with react on it. All of the examples for React Router 4 seem to operate under the assumption that I have access to the props that have stored the previous location already.

So basically, I want to know if there is a way that I can get the current location regardless of where the component is being rendered, so that I can use it as the relative path, where the relative path is the base route for the router (in this case the settings page)

Here is my implementation

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Switch, Link  } from 'react-router-dom';
import Settings from '../components/Settings';
import Permissions from '../components/Permissions';

ReactDOM.render((
   <Router>
      <div>
      <ul>
        <li>
          <Link to="/">Settings</Link>
        </li>
        <li>
          <Link to="/permissions">Permissions</Link>
        </li>
      </ul>
      <hr />
      <Route exact path="/" component={Settings} />
      <Route path="/permissions" component={Permissions} />
      </div>
   </Router>
 ), document.getElementById('reactcomponentwithapidata'));

Upvotes: 1

Views: 1421

Answers (1)

user6612182
user6612182

Reputation:

Try adding basename to your Router component with value /settings.

<Router basename="/settings">
    { /* ... */ }
</Router>

From the documentation:

The base URL for all locations. If your app is served from a sub-directory on your server, you'll want to set this to the sub-directory. A properly formatted basename should have a leading slash, but no trailing slash.

Upvotes: 1

Related Questions