Reputation: 731
I have a React web app and I'm trying to use React Router to navigate between screens.
This is the route configuration in the App component:
render() {
return (
<Router>
<Switch>
<Route exact path="/">
<MainScreen />
</Route>
<Router path="/about">
<About />
</Router>
</Switch>
</Router>
);
};
Somewhere in MainScreen
I navigate to the About component, and it works:
this.props.history.push("/about");
But when I try to navigate back to MainScreen
from the About
page by pushing "/", it changes the URL in the browser, but does not render MainScreen
(I keep seeing the About
page).
I'm using withRouter()
when exporting both MainScreen
and About
.
Upvotes: 1
Views: 47
Reputation: 15688
It's because you have more than one Router
, where once you navigate to the inner-Router
, there is no home Route for "/"
defined in it, so there's no component to render. The Routers
only communicate within their own scope in a top-down like pattern. In the grand scheme of things, you really only need one Router
for your entire application so that all defined Routes
can effectively communicate with each other.
render() {
return (
<Router>
<Switch>
<Route exact path="/" component={MainScreen}>
<Route path="/about" component={About}/>
</Switch>
</Router>
);
};
Upvotes: 1