Reputation: 2840
My question is concerning the react-router-dom
in conjunction with deployment to a relative path (see https://create-react-app.dev/docs/deployment#building-for-relative-paths). On my dev environment the router is working fine, but once i build and deploy my application with the homepage
tag set in package.json
the router does not seem to work anymore.
First of all i would assume that it would be working. After all it's a build option by react to make a build for a specific url and i would assume the same functionality with that relative path in place. However neither the <Link to="">
parts nor the <Switch>
do respect the relative path of my react app.
Second of all i have not found a solution to circumvent this behavior. Any ideas?
Other question dealing with react router and relative paths are focusing on a totally different topic. So i have not found an answer to my question. This React-router app deployed on different locations (subdirectories) is maybe getting close and could be a way to deal with that.
For info:
"react-dom": "^16.8.6",
"react-router-dom": "^5.0.1",
EDIT and PS:
I would probably just need to set a basename. If the basename is changing i would at least want to infer it from the setting in the package.json
and not change my code depending on some package.json
setting.
EDIT 2:
I could use basename={process.env.PUBLIC_URL}
to set the basename to the correct URL. However the routes are still not matching. The links however appear to be fine, so <Link to="/xx">
would actually result in an link to {process.env.PUBLIC_URL}/xx
which is the desired behavior, but the routers <Switch>
does not match them. Actually this is the answer and you can scratch that.
Using basename={process.env.PUBLIC_URL}
does solve my problem.
Upvotes: 10
Views: 4453
Reputation: 410
For me, basename={process.env.PUBLIC_URL} doesn't work. But
<Router basename={window.location.pathname.replace(/(\/[^/]+)$/, "")}>
does the magic, without trailing slash as required in docs: https://reactrouter.com/web/api/BrowserRouter/basename-string
example
var pathname = "/pathname/routeName"
console.log(pathname.replace(/(\/[^/]+)$/, "") //returns /pathname
Upvotes: 5
Reputation: 2840
To anyone stumbling across the same problem: Read the edits in my original question. Using basename={process.env.PUBLIC_URL}
does solve my problem.
Upvotes: 10