Hossein Dehghan
Hossein Dehghan

Reputation: 63

why don't work react-router-dom after build?

links doesn't work after being build but it works in localhost:3000

I use react-router-dom component

build project with :

npm run build

app.js:

    return (  
      <div>
        <Router >
          <Header/>
              <Route exact path="/" component={Home}/>
              <Route path="/about" component={About}/>
              <Route path="/join" component={Join}/>
              <Route path="/advertisement" component={Advertisement}/>
              <Route path="/contact" component={Contact}/>
              <Route path="/details" component={Details}/>

        </Router>
      </div>
    );
  }

and links in other components:

<ul>
    <li><Link to='/'>home</Link></li>
    <li><Link to='/about'>about us</Link></li>
    <li><Link to='/join'>join</Link></li>
    <li><Link to='/advertisement'>ads</Link></li>
    <li><Link to='/contact'>contact us</Link></li>
</ul>

package.json

"homepage": ".",

Upvotes: 6

Views: 9971

Answers (2)

Naveen Jain
Naveen Jain

Reputation: 1072

There is a very specific reason behind this scenario.

1st solution : react is a single page application so when you have build the application , server know only about index.html so for any other url you will have to configure server for fallback mechanism to index.html and after react app will take care of url handling.

2nd solution: if you use hash router than this issue will not occur.
the reason behind using hash router is know more about hashrouter and it's use cases

import { HashRouter as Router, Route, Switch } from "react-router-dom" 

Upvotes: 8

Kishan Jaiswal
Kishan Jaiswal

Reputation: 664

import { Route, BrowserRouter, Switch } from 'react-router-dom';

add switch from this library

  <div>
    <BrowserRouter >
       <Switch>
      <Header/>
          <Route exact path="/" component={Home}/>
          <Route exact path="/about" component={About}/>
          <Route exact path="/join" component={Join}/>
          <Route exact path="/advertisement" component= 
           {Advertisement}/>
          <Route exact path="/contact" component={Contact}/>
          <Route exact path="/details" component={Details}/>
     </Switch>
    </BrowserRouter>
  </div>

try adding this way ,switch is required to wrap the Route component,hope this will help you

Upvotes: 0

Related Questions