next/router
is not working as expected. Instead of redirecting, it is throwing the error mentioned in the title.
index.js
page with following codeimport Router from 'next/router'
export default (props) => {
Router.push('/hola')
return (
<div>
Hi
</div>
)
}
It should show the 404 page as 'hola.js' is not there.
No, the error is perfectly fine because the page get rendered in the server if you want this code to work put Router.push('/hola')
inside componentDidMount
or access to this page from another page with a Link
If one has to put Router.push('/hola')
inside componentDidMount
, how does the following official example work then?
import Router from 'next/router'
function ReadMore() {
return (
<div>
Click <span onClick={() => Router.push('/about')}>here</span> to read more
</div>
)
}
export default ReadMore
You're calling the function inside of render, meaning it's called for every single time render
is called.
<span onClick={() => Router.push('/about')}>here</span>
Above means the equivalent of:
<span onClick={function() { Router.push('/about') }}>here</span>
As you can see it's a function inside of render. Which is only triggered when triggering onClick
is called, which in turn only happens on the client side.
Hi,
useRouter
hook solved my problem. Can you look at Next.js official docs link: https://nextjs.org/docs#userouter
Following below solution, solved my problem :)
I used typeof window !== 'undefined' && Router.pushRoute(...)
. It works.
Why This Error Occurred
During SSR you might have tried to access a router method push
, replace
, back
, which is not supported.
Possible Ways to Fix It
Move any calls to router methods to componentDidMount
or add a check such as typeof window !== 'undefined'
before calling the methods
Source: https://github.com/vercel/next.js/blob/master/errors/no-router-instance.md
You can use this workaround:
if (process.browser){
//Runs only on client side
}
Finally implemented a working solution for this.
First Check whether its a server or not!
if(!(typeof window === undefined)) {
window.history.pushState(null, null, url);
window.location.reload(true);
}
This will first replace the current url with provided url and the reloads the page which works exactly same as Router.push(url)
.
Correct me if I am missing something and is the an acceptable alternate for the issue?
Most helpful comment
No, the error is perfectly fine because the page get rendered in the server if you want this code to work put
Router.push('/hola')
insidecomponentDidMount
or access to this page from another page with a Link