vercel / next.js

The React Framework
https://nextjs.org
MIT License
125.84k stars 26.85k forks source link

router.push from `next/navigation` does not work in a client component #64231

Closed maheshj01 closed 6 months ago

maheshj01 commented 6 months ago

Link to the code that reproduces this issue

https://github.com/maheshmnj/my-app

To Reproduce

  1. clone this project: https://github.com/maheshmnj/my-app
  2. Run the app using npm run dev
  3. When the app loads at localhost:3000. click the login button (Works)
  4. on the Login Page Click Login button (It fails)

Both the steps 3, 4 use

router.push("/myroute")

I also tried routing using window api it doesn't work either

window.location.href = "/dashboard";

project creation logs

mahesh@Maheshs-MacBook-Air-M1-3 ig_schedular % npx create-next-app@latest
✔ What is your project named? … my-app
✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like to use `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to customize the default import alias (@/*)? … No / Yes
Creating a new Next.js app in /Users/mahesh/Development/ig_schedular/my-app.

Using npm.

Initializing project with template: app-tw 

Installing dependencies:
- react
- react-dom
- next

Installing devDependencies:
- typescript
- @types/node
- @types/react
- @types/react-dom
- autoprefixer
- postcss
- tailwindcss
- eslint
- eslint-config-next

Let me know if you need any further info

Current vs. Expected behavior

Actual Result: Routing fails no error in console and page refreshes

Expected Result: Routing should work or atleast show some error in console

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.3.0: Wed Dec 20 21:30:27 PST 2023; root:xnu-10002.81.5~7/RELEASE_ARM64_T8103
Binaries:
  Node: 20.10.0
  npm: 10.2.3
  Yarn: 1.22.19
  pnpm: N/A
Relevant Packages:
  next: 14.1.4
  eslint-config-next: 14.1.4
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.4.4
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

App Router, Routing (next/router, next/navigation, next/link)

Which stage(s) are affected? (Select all that apply)

next dev (local)

Additional context

No response

angeles-renjo commented 6 months ago

const handleLogin = (event: React.FormEvent) => { event.preventDefault(); // Handle login logic here console.log("Logging in with email:", email, "and password:", password); router.push("/dashboard"); };

When you clicked "Login," the form tried to submit to the server by default. To run your custom login logic instead, you need to prevent the default form submission with event.preventDefault(). This allows your login logic to execute, like navigating to the /dashboard page