Home > Enterprise >  I'm having trouble with NextJs useRouter
I'm having trouble with NextJs useRouter

Time:05-01

I'm having trouble with NextJs useRouter.

I have a function to navigate between paths, and I use useRouter to do that, I wrote in a library that contains an array object:

router = useRouter()

const actions = [
  {
  ...
    perform: (e) => router.push('/'),
  ...
  }
]

But it causes the error TypeError: Cannot read properties of null (reading 'useContext')

  2 | import {useRouter} from 'next/router'
  3 | 
> 4 | const { router } = useRouter()
    |                            ^
  5 | 
  6 | const actions = [
  7 |   {

I imported this library to another component, this is what the _app.js looks like:

...
<div className={'webkit selection' theme}>
   <CmdBar theme={theme}/>  => this is where the library imported in
   <Metatags description='null'/>
   <StyleReset/>
   <Component themeUse={themeUse.styles} theme={theme} {...pageProps} />
   <Bar theme={theme} setTheme={setTheme} setThemeUse={setThemeUse} themeProvider={themeProvider}/>
</div>
...

I have had this error the same as I used useLocation in React and React Router before because the components are outside the Route. I think it's the main causes of these.

Edited: It won't keep the same UI if I use anything that can refresh the page, so this is what I want to figure out.

Thank you!

CodePudding user response:

From what I can tell, you're calling useRouter immediately after imports and not inside your component. Hooks need too be called inside React functional components.

https://reactjs.org/docs/hooks-rules.html

i.e.

import { useRouter } from 'next/router'
 
const actions = [..]

const Component = () => {
     const router = useRouter() // use it here

     ...
}

CodePudding user response:

Hi the issue is occuring because you're using a react hook on top level. Instead you should be using the hook inside your React Functional component.

Something like this:

import { useRouter } from 'next/router'

function ActiveLink({ href }) {
  const router = useRouter()

  return (
    <a href={href}>
      This will redirect
    </a>
  )
}

export default ActiveLink

I'd recommend you to go through, Rules of Hooks

  • Related