J.Ko
J.Ko

Reputation: 8801

reactjs/react-router-dom: Browserrouter routing question

this is probably a very simple issue but I cannot find an answer from my searching.

I am writing an app using ReactJs and am using react-router-dom's browserrouter for routing.

When I enter '/login' as URL, the below code will return Profile component, instead of intended Login component. How do I ensure that this will land to Login component as intended?

import React from 'react';
import { BrowserRouter, Route } from "react-router-dom";
import Home from "./routes/Home";
import Profile from "./routes/Profile";
import Post from "./routes/Post"
import Login from "./routes/Login"

function App() {
  return (
    <BrowserRouter>
        <Route path="/" exact={true} component={Home}/>
        <Route path="/login" exact={true} component={Login}/>
        <Route path="/r/:postid" exact={true} component={Post}/>
        <Route path="/:username" exact={true} component={Profile}/>
    </BrowserRouter>
  );
}

export default App; 

Upvotes: 0

Views: 63

Answers (1)

asmaa
asmaa

Reputation: 725

You can use Switch instead, as it Renders the first child <Route> or <Redirect> that matches the location.

Example:

<BrowserRouter>
    <Switch>
        <Route path="/" exact={true} component={Home}/>
        <Route path="/login" exact={true} component={Login}/> 
    </Switch>
</BrowserRouter>

Upvotes: 1

Related Questions