Nasridean
Nasridean

Reputation: 45

React Router: Route with path='/' is not working

I have this route:

const AppRouter = () => (
    <Router history={history}>
    <div>
        <Switch>
            <Route path='/' component={LoginPage} exact={true} />
        </Switch>
    </div>
    </Router>
);

It only works when I set Route path to an empty string '' However, logging history.location.pathname shows / It is run on localhost:3000

I noticed that this one works:

<Route path=':3000/' component={LoginPage} exact={false} />

Upvotes: 1

Views: 212

Answers (2)

Harshal Choudhary
Harshal Choudhary

Reputation: 36

you also don't have to include '/' in browser window after 'localhost:3000'.

import React from 'react'  
import { BrowserRouter, Route, Switch } from "react-router-dom";
import ComponentName from './ComponentName';

const Router = () => {
<BrowserRouter>   
 <Switch>
          <Route exact path="/" component={ComponentName}/>
   </Switch>
</BrowserRouter>
}
export default Router;

after that import Router Component to the App.js.

import Router from './Router';
function App() {
  return <Router /> 
} 
export default App;

Upvotes: 2

Arkadip Bhattacharya
Arkadip Bhattacharya

Reputation: 642

I don't know, what your codebase is actually doing, but as much as I know, it should work. If it is not, then you might done a mistake.

First of all, you should use react-router-dom, not react-router

Then for a react app, the routing component look something like this

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

const AppRouter = () => (
    <Router>
    <div>
        <Switch>
            <Route path='/' component={LoginPage} exact={true} />
        </Switch>
    </div>
    </Router>
);

This should work properly. If it's not, then let me know

Upvotes: 0

Related Questions