#Error: NextRouter was not mounted.
1 messages · Page 1 of 1 (latest)
Hmm, I don't know enough to give you a confident answer yet. However, the error message you're seeing typically indicates that the Next.js router is not properly initialized or used in your application.
You can use the useRouter or withRouter functions to access the router object in your components. Here are some examples from the Next.js documentation (https://nextjs.org/docs/pages/api-reference/functions/use-router):
Using useRouter:
import { useEffect } from 'react'
import { useRouter } from 'next/router'
export default function MyApp({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
const handleRouteChange = (url, { shallow }) => {
console.log(
`App is changing to ${url} ${
shallow ? 'with' : 'without'
} shallow routing`
)
}
router.events.on('routeChangeStart', handleRouteChange)
// If the component is unmounted, unsubscribe
// from the event with the `off` method:
return () => {
router.events.off('routeChangeStart', handleRouteChange)
}
}, [router])
return <Component {...pageProps} />
}
Using withRouter:
import { withRouter } from 'next/router'
function Page({ router }) {
return <p>{router.pathname}</p>
}
export default withRouter(Page)
If you're still having trouble, you might find it helpful to review the Next.js routing documentation (https://nextjs.org/docs/app/building-your-application/routing).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@pearl trellis kapa.ai is still learning and improving, please let us how it did by reacting below
Let me check the knowledge base for you. One moment! :books:
Sorry @low gazelle, I seem to be having a bit of trouble. Don't worry though, I've pinged my supprt and they will try to fix me up! :technologist:
Perhaps try again in 15mins?
Let me check the knowledge base for you. One moment! :books:
The error message you're seeing typically indicates that you're trying to use a hook outside of a React component or not within the body of a function component.
In your case, it seems like there might be a typo in your code. The correct function to use is useRouter(), not userRouter(). Here's how you can use it in a function component:
import { useRouter } from 'next/router'
function ActiveLink({ children, href }) {
const router = useRouter()
const style = {
marginRight: 10,
color: router.asPath === href ? 'red' : 'black',
}
const handleClick = (e) => {
e.preventDefault()
router.push(href)
}
return (
<a href={href} onClick={handleClick} style={style}>
{children}
</a>
)
}
export default ActiveLink
This example is taken from the Next.js documentation (https://nextjs.org/docs/pages/api-reference/functions/use-router).