Nextjs link onClick: Routing and Form Submission Examples

hamzarahman

Hamza Rahman

Posted on October 9, 2024

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

💖 💪 🙅 🚩
hamzarahman
Hamza Rahman

Posted on October 9, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related