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
)
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
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} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With