React Router v4 routes not working

While using Switch we need to keep in mind that we specify the routes to be from most specific to most generic. In your case, you have specified "/" before "/about". So every time react is looking for "/about" but going down <Route "/" satisfies for "/about" as well (because "/about" is sub-route of "/") So use: "/about" before "/"

This way you can omit exact as well

import React from 'react';
import ReactDOM from 'react-dom';

import {BrowserRouter as Router, Route, Switch, IndexRoute, Link} from 'react-router-dom';

const Home = () => <h1><Link to= "/about">Click Me</Link></h1>
const About = () => <h1>About Us</h1>

const Test = () => (
  <Router>
    <Switch>
        <Route path ="/about" component = {About} />
        <Route path ="/" component = {Home} />
    </Switch>
  </Router>
)

ReactDOM.render(<Test />, document.getElementById('app'));

You need to use an exact path for / otherwise it will also match /about.

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

As mentioned in the comments, for something this simple I would suggest using Create React App which will make sure your server code and your webpack settings are all correct. Once you use create-react-app you'll just need to use npm to install the react router v4 package, and then put your code above into the App.js file and it should work. There are some small changes to your code to get it to work with create-react-app as can be seen below:

// App.js
import React from 'react';

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

const Home = () => <h1><Link to="/about">Click Me</Link></h1>
const About = () => <h1>About Us</h1>

const App = () => (
  <Router>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
    </Switch>
  </Router>
)

export default App;

The quick start instructions from React Router V4 documentation will tell you pretty much the same as I just explained.


If you're running from localhost you need to add historyApiFallback: true to your webpack.config file


if Adding exact Don't resolve issue, i have replaced this with

  <Route exact path="/" component={App} />
  <Route path="/login" component={Login} />
  <Route path="/register" component={Register} />

This one

  <Route exact path="/"> <App /> </Route>
  <Route path="/login"> <Login /> </Route>
  <Route path="/register"> <Register /> </Route>

putting component as Route Child solves my page routing i hope it helps someone else too