Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

router.push() is not working as expected NextJS

I am trying to redirect the user to the search results, but router.push() is not working apparently. I changed url to page that don't exist and the route changes, but when it comes to using the url of page already created, nothing happens.

I tried doing something like this, but it's not working either.

import { useRouter } from 'next/router';
const router = useRouter();

const search = () => {
    router.push('/search');
    };
}
like image 431
Thamagik Avatar asked Dec 05 '25 15:12

Thamagik


2 Answers

If you are using Nextjs13, please be aware to import useRouter from next/navigation:

❌ import { useRouter } from 'next/router';

to:

✅ import { useRouter } from 'next/navigation';

Documentation link

like image 50
Attaque Avatar answered Dec 08 '25 07:12

Attaque


The solution here is to prevent default function by doing something like this:

import { useRouter } from 'next/router';
const router = useRouter();

const Search = (e) => {
        e.preventDefault()
        router.push("/search");
    };
like image 37
Thamagik Avatar answered Dec 08 '25 08:12

Thamagik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!