Home Web Front-end JS Tutorial Nextjs link onClick: Routing and Form Submission Examples

Nextjs link onClick: Routing and Form Submission Examples

Oct 09, 2024 pm 10:50 PM

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>
    </Link>
  );
}
Copy after login

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={link} onClick={handleClick}>
      Handle Click
    </a>
  )
}

export default ClickExample
Copy after login

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={link} onClick={handleClick}>
      Handle Click
    </a>
  )
}

export default ClickExample
Copy after login

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 (
    <form onSubmit={handleSubmit}>
      <input
        type='text'
        name='username'
        onChange={e => {
          setUsername(e.target.value)
        }}
      />
      <input
        type='password'
        name='password'
        onChange={e => {
          setPassword(e.target.value)
        }}
      />
      <button type='submit'>Login</button>
    </form>
  )
}
Copy after login

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
Copy after login

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
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles