Muhammad Ali
Muhammad Ali

Reputation: 3536

React routing not working v4

I'm trying to route multiple pages using BrowserRouter. Many of the guides online are outdated and do not work with Reactv4. Here's what I'm doing:

Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Route, Switch} from 'react-router-dom'
import SignIn from './components/SignIn';
import SignUp from './components/SignUp';
import ForgotPass from './components/ForgotPass';

ReactDOM.render((<BrowserRouter>
  <Switch>
    <Route path="/" component={SignIn}/>
    <Route path="/signup" component={SignUp}/>
    <Route path="/forgot" component={ForgotPass}/>
  </Switch>
</BrowserRouter>), document.getElementById('root'));

And then I create hyperlinks to those pages using:

<a href="/forgot">Forgot password?</a>

But when I click the hyperlink it just loads the same page again.

Also: I've seen some guides use the App component, I wasn't sure if that is something predefined in React and if it was needed, as I need the SignIn component to be the default page.

Upvotes: 0

Views: 35

Answers (1)

nbwoodward
nbwoodward

Reputation: 3156

Put the exact flat on your root path. Otherwise it will match in the switch before it gets to the lower routes.

 <Switch>
    <Route exact path="/" component={SignIn}/>
    <Route path="/signup" component={SignUp}/>
    <Route path="/forgot" component={ForgotPass}/>
 </Switch>

OR move it to the end:

<Switch>
    <Route path="/signup" component={SignUp}/>
    <Route path="/forgot" component={ForgotPass}/>
    <Route path="/" component={SignIn}/>
 </Switch>

Upvotes: 2

Related Questions