Reputation: 41
I wrote a React app in which I'm using react-router-dom and Link and Route pairs like
<Link to="/subpath"> <Route path="/subpath">
or
<Link to="/basepath/subpath"> <Route path="/basepath/subpath">
In development links and routes with and without /basepath work fine. However, after npm run build, only the first load of the base URL works. Anything I do on the app causes the basepath to disappear from the URL. For example if I click a
<Link to="/subpath">
or
<Link to="/basepath/subpath">
, which both should take me to
https://domain/basepath/subpath
, I end up in
https://domain/subpath
The app kind of keeps working, but images cannot be found no more and for example the page refreshes naturally fail.
I have tried everything I've found from the internet that might affect this, like adding basename to the BrowserRouter, set the homepage to package.json, build with PUBLIC_URL, and add basepath to every Link and Route tag. (I even tried giving the basepath in Link tag twice, but both basepaths disappeared from the URL. :-) )
How can I get the React Router to keep the basepath in the URL?
EDIT: Sample link-route pair:
<Link to={"/somepath/path/" + someId}>
<img src={"https://domain/somepath/" + image + ".jpg"} />
</Link>
<Route path="/somepath/path/:someId">
<ShowImage />
</Route>
The link and route paths can also be without /somepath, ie. "/path/...", makes no difference in development, but neither work in production.
Clicking the link should make the browser go to https://domain/somepath/path/someId
,
but it goes to
https://domain/path/someId
The app and routing seems to work sort of fine, as it next shows ShowImage. However, at the same time the image source apparently becomes
https://domain/image.jpg
as ShowImage cannot find the same image from the same source address.
EDIT 2:
The router structure.
<Router>
<Switch>
<Route path="/somepath/:someId">
<ShowImage />
</Route>
<Route path="/">
<ShowBase />
</Route>
</Switch>
</Router>
ShowBase and ShowImage code to display an image.
<img src={"https://domain/basepath/" + image + ".jpg"} />
ShowImage history.push (with or without /basepath) and button handling.
function handleClick(event) {
history.push('/');
}
<button onClick={handleClick}>Back</button>
Upvotes: 2
Views: 2273
Reputation: 41
I think I figured it out. A link to the build directory had disappeared and this caused the problems. After recreating the link, it was easy to get everything to work as expected. Sorry it took so long.
Upvotes: 1
Reputation: 3486
If I get your problem, you try to put an image id in the url and go to the "basepath" with the image id. (and in the component get the params and display the image)
you can use redirect like this
<Redirect exact from="/:id" to="/basepath/:id" />
Upvotes: 0