Reputation: 393
I am trying to do a very basic routing process where I have a home page, and on this home page when clicking on a button I get redirected to the next page. I have 3 components - "App, HomePage, and NextPage". I am using a history object to push the new URL, and this part works.
However, I am not sure how to actually call the new route (e.g. make the App component render the new route. My code is as follows:
export default function App() {
return (
<Router>
<div>
<Switch>
<Route path="/">
<HomePage/>
</Route>
<Route path="/nextpage">
<NextPage/>
</Route>
</Switch>
</div>
</Router>
);
}
function HomePage () {
let history = useHistory();
function handleClick() {
history.push("/nextpage");
}
return (
<div>this is the home page
<button type="button" onClick={handleClick}>Display next page</button>
</div>
)
}
export default withRouter(HomePage);
function NextPage () {
return (
<div>You just arrived to the next page!</div>
)
}
export default NextPage;
Any idea what step I am missing? I have read the documentation but I am not clear who exactly triggers the rendering on the NextPage component, since clicking the button only modifies the history object.
Upvotes: 1
Views: 261
Reputation: 889
I see now! Your code is not rendering the nextpage because the condition for the HomePage is still true, try to add "exact" to your first route, like this:
<Route exact path="/">
<HomePage/>
</Route>
That's because when you use Switch it will render when the first Route condition returns true and will stop there. Some reference: https://reacttraining.com/react-router/core/api/Prompt Happy coding! :D And welcome to Stack Overflow!!!
Upvotes: 2