Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import Router from 'next/router' is it ok?

Next.js documentation mentions two ways to access the router object: useRouter for functional components and withRouter for class-based components.

However, it does not mention something I came across a few times which is the Router object accessed as follows, for example:

import Router from 'next/router'

Router.push("/")

Is it correct to use Router in this way? Why doesn't Next.js documentation mention it?

like image 953
fredperk Avatar asked Oct 12 '20 20:10

fredperk


People also ask

How do I use a custom router in next router?

You can pass a custom Router class, Link component or getRouterMatchFunction to the init function if you need to. They will be used instead of the built ins with import { Link, Router } from '@nx/next-router';. If you use a custom server you can create more complex routes and are not limited by what you can do with Next.js default routing.

Is it possible to use browserrouter as a switch router?

Yes, and it's up to you. I usually put mine in index.js but so long as it is above all the Switch and Route components it does not matter. The import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; is 100% valid and what you should be importing.

Why can't I use next/router directly from the object itself?

I guess the main suggestion to not use Router.push () or Router.pathname directly from the object itself is because of the way Next.js serves the applications. When you're trying to do: You will receive an error with: You should only use "next/router" inside the client side of your app. This is because of the way next/router works with SSR.

What is the router object returned by userouter?

The following is the definition of the router object returned by both useRouter and withRouter: pathname: String - Current route. That is the path of the page in /pages, the configured basePath or locale is not included.


1 Answers

I guess the main suggestion to not use Router.push() or Router.pathname directly from the object itself is because of the way Next.js serves the applications. When you're trying to do:

import Router from 'next/router';

const HomePage = () => {
  console.log(Router.pathname);

  return (
    <div>hi</div>
  )
}

You will receive an error with: You should only use "next/router" inside the client side of your app. This is because of the way next/router works with SSR.

You could however put this in an useEffect and it will work... but that's hacky and you will probably run into issues in the future.

Both useRouter and withRouter are Next.js their solution to this problem. They are both build so they can work with SSR and CSR. So my suggestion is just to use one of these, they work great 🙂.

like image 141
Rowin Avatar answered Oct 17 '22 05:10

Rowin