-
Notifications
You must be signed in to change notification settings - Fork 27.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs: enhanced
next-router-not-mounted
error page
- Loading branch information
Showing
1 changed file
with
19 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,28 @@ | ||
# NextRouter was not mounted | ||
# `NextRouter` was not mounted | ||
|
||
#### Why This Error Occurred | ||
|
||
A component used `useRouter` outside a Next.js application, or was rendered outside one. This can happen when doing unit testing on components that use the `useRouter` hook as they are not configured with Next.js' contexts. | ||
A component that used `useRouter` was rendered outside the `pages/` directory. This can happen when migrating to the `app/` directory. Situations where you also render components outside a Next.js application (like in unit tests) can also trigger this error. | ||
|
||
#### Possible Ways to Fix It | ||
|
||
If used in a test, mock out the router by mocking the `next/router`'s `useRouter()` hook. | ||
If you're migrating components over from `pages/` to `app/`, you can take advantage of the compatibility hooks that are designed to be used in transition when components are shared between `pages/` and `app/`. Instead of writing: | ||
|
||
```tsx | ||
import { useRouter } from 'next/router' | ||
``` | ||
|
||
You would write: | ||
|
||
```tsx | ||
import { useRouter } from 'next/compat/router' | ||
``` | ||
|
||
When the router context is not available, this hook will return `null` instead of throwing an error. Developers should migrate over to the new router hook available at `next/navigation` which is fully supported in `app/`. | ||
|
||
If you're unit testing components that rely on these hooks, you should mock the the `next/router`'s `useRouter()` hook instead. | ||
|
||
### Useful Links | ||
|
||
- [next-router-mock](https://www.npmjs.com/package/next-router-mock) | ||
- [`next-router-mock`](https://www.npmjs.com/package/next-router-mock) | ||
- [`useRouter` from `next/navigation`](https://beta.nextjs.org/docs/api-reference/use-router) |