ReactJS routing issue after deployment in production

Viewed 677

I have some routing issues for my ReactJS application post deploying into a subdirectory in production domain.

I am placing the build files into directory www.xyz.com/folder1/appfolder/ on my website and my homepage attribute in package.json is set to the same path. I have also tried to use manifest.json "start_url": "./dashboard" And my application file has route defined as below

<Route exact path="/" component={DashboardPage} />

Expected: When I run on localhost everything works fine as in the default page is the dashboard page when I visit localhost. But in production when I visit

www.xyz.com/folder1/appfolder/

i expect the dashboard page to load up but it doesn't load but a blank page comes up with all left nav, header, footer with no content. Once I click on Dashboard link in side nav then the page loads up but with this URL

www.xyz.com/appfolder/ (missing folder1 in path)

If I take this below path and visit directly then its broken as well

www.xyz.com/appfolder/

Only when I visit below and then click on side navbar dashboard link then it redirects to just app folder and the page loads up.

www.xyz.com/folder1/appfolder/

Kindly suggest as something really basic is missing due to which I am facing this problem. its a bad user experience.

2 Answers

Set basename prop in your BrowserRouter

<BrowserRouter basename='folder1'>
...routes...
</BrowserRouter>

Try using hashrouter instead of browser router.

So in your app.js (if this is where you have your routes defined)

Change the import like this

FROM

import { BrowserRouter } from 'react-router-dom'
...
<BrowserRouter>
  <Switch>
    <Route exact path="/" component={DashboardPage} />
    ....
  </Switch>
</BrowserRouter>

TO

import { HashRouter } from 'react-router-dom'
...
<HashRouter>
  <Switch>
    <Route exact path="/" component={DashboardPage} />
    ....
  </Switch>
</HashRouter>
Related