useRouter
Your codebase includes a convenient useRouter
hook that enables you read the current path, get the query string as an object, and programmatically change routes. If you've exported with the default React option we give you a custom hook that wraps the lower-level React Router hooks and does some extra nice things for you (such as scroll to the top of the page on route transition). If you've exported your project with our Next.js framework option then we use use the useRouter
hook from next/router directly.
Here's an example that illustrates how easy it is:
import { Link, useRouter } from './../util/router.js';
function MyComponent(){
// Get the router object
const router = useRouter();
// Get value from query string (?postId=123) or route param (/:postId)
console.log(router.query.postId);
// Get current pathname
console.log(router.pathname)
// Navigate with the <Link> component or with router.push()
return (
<div>
<Link to="/about">About</Link>
<button onClick={(e) => router.push('/about')}>About</button>
</div>
);
}
Files
src/util/router.js
Any questions you have that aren't answered here? Please reach out and let us know. We'll answer your question and then improve the docs for others.