Ad

React BrowserRouter Route Is Not Working After Deploy

- 1 answer

I have a simple website and have 2 links which is working offline but if i deploy it and upload it on a website then the first page is working fine but when i click on add Link then it's giving me 404 and list link is working fine and both link is working fine on offline

<a target="_blank" rel="nofollow noreferrer" href="/react/">List</a>
<a target="_blank" rel="nofollow noreferrer" href="/react/Add">Add</a>

Router file

ReactDOM.render(
  <BrowserRouter>
    <Route path="/react/" exact component={List}/>
    <Route path="/react/Add" exact component={Add}/>
  </BrowserRouter>,
  document.getElementById('root')
);

Package.json

{
    "name": "axios1",
    "version": "0.1.0",
    "homepage":"http://aroratour.com/react/",
Ad

Answer

As you have deployed your project in sub-folder called react. You need to add basename to your BrowserRouter and need to remove /react from your Route's path,

<BrowserRouter basename="/react">
    <Switch> // Switch return the first matching Route
      <Route path="/" exact component={List}/>
      <Route path="/Add" exact component={Add}/>
    </Switch>
</BrowserRouter>

Note: Make sure to add .htaccess file.

If you have any Link in your project, that should not include /react in path.

For example, to navigate to /Add using Link, you should have,

<Link to="/Add"> Add </Link>

This will internally get's converted to,

<a target="_blank" rel="nofollow noreferrer" href="/react/Add"> Add </a>   //React will automatically add `/react` from basename in BrowserRouter

Update

This .htaccess content works for me,

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/index.html$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !\.(css|gif|ico|jpg|js|png|swf|txt|svg|woff|ttf|eot)$
RewriteRule . index.html [L]
Ad
source: stackoverflow.com
Ad