Nextjs link routing onClick and login form example

Authors
  • avatar
    Name
    Hamza Rahman
Published on
-
4 mins read
Tags:
nextjs

In this nextjs redirects tutorial, we will look how to route to another link based on click(onClick) or form submission. I have updated (May 2024) the code to include both vanilla js and TypeScript version of the examples.

Nextjs onClick redirect

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

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

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>
)
}

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

In this simple login form example, we can see how 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.