Home > Blockchain >  React Router Dom removes the url sub paths instead of adding the routing page
React Router Dom removes the url sub paths instead of adding the routing page

Time:02-03

I have an asp.net MVC application that serves the React app under the following url: http://domain.fake/controller/action. Here is the routing of the react app:

<Routes>
 <Route path="/*" element={<Config />}>
   <Route path="values" element={<ConfigKeyValues />} />
 </Route>
</Routes>

When I try to navigate to the values route using the useNavigate hook:

const nav = useNavigate();
nav("values");

In the URL, instead of adding the /values path, the routing removes the whole controller/action path and only sets the /values path. So instead of getting the url http://domain.fake/controller/action/values, I'm getting http://domain.fake/values, and this is not right.

I'm able to display the component correctly, and I'm not being redirected by the server, but the url is wrong because I can't share that since it does not exist.

How can I prevent the React routing from replacing the base path but adding the new path to the url and displaying the component of that route?

CodePudding user response:

To tell React Router Dom that your application is served from a subfolder, you could use the basename property, which works with createBrowserRouter as well as BrowserRouter:

The basename of the app for situations where you can't deploy to the root of the domain, but a subdirectory.

<BrowserRouter basename="/controller/action">
  {/* The rest of your app goes here */}
</BrowserRouter>
createBrowserRouter(routes, {
  basename: "/controller/action",
});

Side note, be aware that calling navigate("values"), without / at the beginning of values would take into account the path you are on and build on top of it as the doc says.

CodePudding user response:

true navigate method inside react-router-dom will clear the sub path so we need to add it manually but this is will be bad if you hard coded it instead we will add it automatically

function YourPage() {
    const nav = useNavigate()
    const location = useLocation()
    return (
        <div>
            <button onClick={() => nav(`${location.pathname}/yourTargetPath`)}>
              Navigate
            </button>
        </div>
    )
}

we will save our sub-path inside the variable and add it to navigate method this should solve your problem

  • Related