search
HomeWeb Front-endJS TutorialNextjs link onClick: Routing and Form Submission Examples

Nextjs link onClick: Routing and Form Submission Examples

In this tutorial, we'll explore how to leverage the power of Nextjs link onClick functionality for programmatic routing. We'll cover various scenarios including click-based navigation, form submissions, and optimizing page transitions. The examples are provided in both JavaScript and TypeScript to cater to different developer preferences.

Table of Contents

  1. Using Next.js Link Component
  2. Simple Click-based Routing
  3. Form Submission and Routing
  4. TypeScript Implementations
  5. Best Practices and Optimization

Using Next.js Link Component

Next.js provides a powerful Link component from the next/link module that allows you to create interactive links in your application. This component enables navigation between pages without triggering a full page reload, which is crucial for maintaining a smooth user experience in a single-page application.

The Link component can be combined with onClick events to create dynamic and interactive navigation experiences. Here's a basic example of how you might use the Link component with an onClick event:

import Link from 'next/link';
import { useRouter } from 'next/router';

export default function NavigationExample() {
  const router = useRouter();

  const handleClick = (e) => {
    e.preventDefault();
    // Perform some action here
    console.log('Link clicked!');
    // Then navigate programmatically
    router.push('/about');
  };

  return (
    <link href="/about">
      <a onclick="{handleClick}">About</a>
    
  );
}

In this example, we're using both the Link component and the useRouter hook. The Link component provides the client-side routing capabilities, while the useRouter hook allows us to programmatically navigate after performing some custom logic in our handleClick function.

This approach gives you the flexibility to execute custom code before navigation occurs, which can be useful for various scenarios such as form validation, data fetching, or state updates.

Now, let's dive deeper into more specific use cases and advanced techniques for handling routing with onClick events in Next.js.

Nextjs onClick redirect

The following example demonstrates how to use the useRouter hook to handle click events for routing:

import { useRouter } from 'next/router'

function ClickExample({ link }) {
  const router = useRouter()

  const handleClick = event => {
    event.preventDefault()
    router.push(link)
  }

  return (
    <a href="%7Blink%7D" onclick="{handleClick}">
      Handle Click
    </a>
  )
}

export default ClickExample

In this example, we use router.push(link) to navigate to the specified link. This method adds the new route to the browser's history stack. If you don't want to save the URL in history, you can use router.replace(link) instead.

Nextjs onClick redirect (TypeScript)

import { FC } from 'react'
import { useRouter } from 'next/router'

interface ClickExampleProps {
  link: string
}

const ClickExample: FC<clickexampleprops> = ({ link }) => {
  const router = useRouter()

  const handleClick = (event: React.MouseEvent<htmlanchorelement>) => {
    event.preventDefault()
    router.push(link)
  }

  return (
    <a href="%7Blink%7D" onclick="{handleClick}">
      Handle Click
    </a>
  )
}

export default ClickExample
</htmlanchorelement></clickexampleprops>

We can utilize useRouter hook to handle click events routing.
Here router.push(link) pushes the link to router history.
If you do not want the link URL to be saved in history,
then router.replace(link) can be used.

Nextjs Login Form example redirect and prefetch

import { useCallback, useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import axios from 'axios'

export default function Login() {
  const router = useRouter()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')

  const handleSubmit = async e => {
    e.preventDefault()

    console.log(username, password)

    if (username && password) {
      const options = {
        method: 'post',
        url: 'http://localhost:3000/login',
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
        },
        data: {
          username,
          password,
        },
      }
      const response = await axios(options)
      if (response.status == '200') {
        router.push('/home')
      }
    }
  }

  useEffect(() => {
    // Prefetch the home page for faster transition
    router.prefetch('/home')
  }, [])

  return (
    
{ setUsername(e.target.value) }} /> { setPassword(e.target.value) }} />
) }

Nextjs Login Form example redirect and prefetch (TypeScript)

import { useState, useEffect, FormEvent, ChangeEvent } from 'react'
import { useRouter } from 'next/router'
import axios from 'axios'

interface LoginResponse {
  status: number
  data: {
    token: string
  }
}

const Login = () => {
  const router = useRouter()
  const [username, setUsername] = useState<string>('')
  const [password, setPassword] = useState<string>('')

  const handleSubmit = async (e: FormEvent<htmlformelement>) => {
    e.preventDefault()

    if (username && password) {
      const options = {
        method: 'post',
        url: 'http://localhost:3000/login',
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
        },
        data: {
          username,
          password,
        },
      }

      try {
        const response = await axios(options)
        if (response.status === 200) {
          router.push('/home')
        }
      } catch (error) {
        console.error('Login failed:', error)
      }
    }
  }

  useEffect(() => {
    router.prefetch('/home')
  }, [router])

  const handleUsernameChange = (e: ChangeEvent<htmlinputelement>) => {
    setUsername(e.target.value)
  }

  const handlePasswordChange = (e: ChangeEvent<htmlinputelement>) => {
    setPassword(e.target.value)
  }

  return (
    <form onsubmit="{handleSubmit}">
      <input type="text" name="username" onchange="{handleUsernameChange}">
      <input type="password" name="password" onchange="{handlePasswordChange}">
      <button type="submit">Login</button>
    </form>
  )
}

export default Login
</htmlinputelement></htmlinputelement></htmlformelement></string></string>

In this simple login form example, we can see how to use Nextjs link onClick to redirect to the home page after a successful login API call.
router.push('/home') will redirect to the homepage, and similarly, on failure, we could redirect to an error page.
Here, router.prefetch('/home') prefetches the home page for a faster transition.
One thing to note is that as useRouter is a hook, it can only be called in a functional component.
The Nextjs link onClick functionality is demonstrated through the use of the router.push() method, which allows for programmatic navigation based on user interactions or form submissions.

Best Practices and Optimization

When working with Next.js link onClick functionality, consider the following best practices:

  1. Use router.push() for most cases: This method adds the new route to the browser's history stack, allowing users to navigate back.

  2. Use router.replace() for login/logout: This replaces the current history entry, preventing users from navigating back to a logged-out state.

  3. **Leverage router.prefetch(): Prefetching can significantly improve perceived performance by loading the target page in the background.

  4. Handle errors gracefully: Always include error handling in your routing logic, especially when dealing with asynchronous operations like API calls.

  5. Use TypeScript for better type safety: TypeScript can help catch potential errors early and improve code maintainability.

Here's an example incorporating these best practices:

import { useRouter } from 'next/router'
import { useState } from 'react'

const OptimizedNavigation = () => {
  const router = useRouter()
  const [isLoading, setIsLoading] = useState(false)

  const handleNavigation = async (event: React.MouseEvent<htmlanchorelement>) => {
    event.preventDefault()
    setIsLoading(true)

    try {
      // Perform any necessary async operations here
      await someAsyncOperation()

      // Use replace for login/logout scenarios
      await router.replace('/dashboard')
    } catch (error) {
      console.error('Navigation failed:', error)
      // Handle error (e.g., show error message to user)
    } finally {
      setIsLoading(false)
    }
  }

  // Prefetch the dashboard page
  useEffect(() => {
    router.prefetch('/dashboard')
  }, [router])

  return (
    <a href="/dashboard" onclick="{handleNavigation}" aria-disabled="{isLoading}">
      {isLoading ? 'Loading...' : 'Go to Dashboard'}
    </a>
  )
}

export default OptimizedNavigation
</htmlanchorelement>

By following these best practices, you can create more robust and performant applications using Next.js link onClick functionality.

The above is the detailed content of Nextjs link onClick: Routing and Form Submission Examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.