Search code examples
reactjstypescriptnext.jsnext-router

NextRouter was not mounted Next.JS


Using import { useRouter } from "next/router"; as import { useRouter } from "next/navigation"; throws "Argument of type '{ pathname: string; query: { search: string; }; }' is not assignable to parameter of type 'string'."

    const router = useRouter();
    const [searchInput, setSearchInput] = useState("");

    const search = (e) => {
                router.push({
                    pathname: '/search',
                    query: {
                        search: searchInput,
                    },
                })
    }

NextJS documentation

Froms docs: "A component used useRouter outside a Next.js application, or was rendered outside a Next.js application. This can happen when doing unit testing on components that use the useRouter hook as they are not configured with Next.js' contexts."


Solution

  • Migrating from the pages directory:

    • The new useRouter hook should be imported from next/navigation and not next/router
    • The pathname string has been removed and is replaced by usePathname()
    • The query object has been removed and is replaced by useSearchParams() router.events is not currently supported.

    Here is the solution: https://beta.nextjs.org/docs/api-reference/use-router