Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router always rendering '/' path

I'm trying to use the v4 react router, but the router always renders the initial path ('/'). I'm using

react: ^16.2.0

react-dom: ^16.2.0

react-router-dom: ^4.2.2

When I try to render /#/account, it renders Home instead of Account.

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

import Home from "./components/Home/Home";
import Account from "./components/Account/Account";
import Layout from "./components/Layout";

const app = document.getElementById('app');

ReactDOM.render(
  <Router>
      <div>
        <Route exact path="/" render={() => (<div>Home</div>)} />
        <Route path="/account" render={() => (<div>Account</div>)} />
      </div>
  </Router>,
  app
)
like image 332
Deepak Bandi Avatar asked Dec 02 '17 23:12

Deepak Bandi


2 Answers

One of the ways to get around this is to make use of <Switch> from react-router-dom, You can import it like :

import {Switch} from 'react-router-dom';

and then wrap your <Route> inside <Switch> i think its a good idea to put "/" in the last and give default component as well like :

  <Router>
      <div>
        <Switch>
          <Route path="/account" render={() => (<div>Account</div>)} />
          <Route exact path="/" render={() => (<div>Home</div>)} />
          <Route component={NoMatch}/>
        </Switch>
     </div>
  </Router>

You can read more about <Switch> Here

like image 82
Aaqib Avatar answered Sep 22 '22 04:09

Aaqib


I know its bit late but was facing same issue and thought of sharing with everyone.

Fixed by adding "exact" parameter to Route

<Route path="/contact-us" exact component={component-name} />
like image 25
aatif shaikh Avatar answered Sep 24 '22 04:09

aatif shaikh