If I click on a navigation link, I can see that the slug has changed but the component is not rendering. I have to manually refresh the page in order to see the component, while the page should re-render by itself on route/slug change.
App.js
import React, { Component } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Me from './components/me';
import Contrib from './components/contrib';
import Projects from './components/projects';
import Contact from './components/contact';
class App extends Component {
render() {
return (
<div className="container">
<BrowserRouter>
<Switch>
<Route exact path="/" component={Me} />
<Route path="/contrib" component={Contrib} />
<Route path="/projects" component={Projects} />
<Route path="/contact" component={Contact} />
</Switch>
</BrowserRouter>
</div>
);
}
}
header.jsx
import { BrowserRouter, NavLink} from 'react-router-dom';
const Header = () => {
return (
<div className="container">
<div id="logo">
<img src={Earth} alt="placeholdit" className="rounded" />
</div>
<nav>
<BrowserRouter>
<ul>
<li><NavLink to="/">Home</NavLink></li>
<li><NavLink to="/contrib">Contributions</NavLink></li>
<li><NavLink to="/projects">Projects</NavLink></li>
<li><NavLink to="/contact">Contact</NavLink></li>
<li></li>
</ul>
</BrowserRouter>
</nav>
</div>
)
}
If I remove the <BrowserRouter>
from header.jsx
I get an error telling me that: "You should not use <Route>
or withRouter()
outside a <Router>
".
If add the <BrowserRouter>
inside of header.jsx
the error is gone, but the components are not rendering on route/slug change.
You need to wrap around the highest order component for it to work as expected. If your app is simple, wrap it within ReactDOM.render method. Like so
ReactDOM.render((
<BrowserRouter>
<App/>
</BrowserRouter>),
document.getElementById('root'))
I had the same problem. Delete the from header.jsx and put it in your index.js like this:
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>
, document.getElementById('root'));
Be careful with the order of Route, Switch and Router. I follow this order and it works for me. Note: Try to use the Arrow function
import React from "react";
import { Switch, Route, Router } from "react-router-dom";
// Containers
import { Dashboard, CardPayment } from "../Containers";
const history = createBrowserHistory();
const ReactRouter = () => {
return (
<Router history={history}>
<Switch>
<Route path="/dashboard" component={Dashboard} exact={true} />
<Route path="/card-payment" component={CardPayment} exact={true} />
<Route path="/" component={Dashboard} exact={true} />
</Switch>
</Router>
);
};
export default ReactRouter;
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