How to use Router Push method In Next.js
If we want to do redirect in a client component on client side event then we can use a push() method of useRouter hook. In Push(new_routePath), we have to pass a route path where we have to redirect after some action. To use a push() method, we have to import useRouter hook from next/navigation.
Example: The below example demonstrate the use of router push method
//page.js
'use client'
import { useRouter } from "next/navigation"
import { useState } from "react"
export default function ClientRedirect() {
const [counter, setCounter] = useState(5)
const router = useRouter()
if(counter == 0){
router.push('/gfg')
}
setInterval(()=>{
setCounter(counter-1)
},1000)
return (
<>
<h1>Time Left {counter}</h1>
</>
)
}
//page.js (gfg directory)
export default function Page() {
return (
<>
<h1>Welcome to w3wiki</h1>
</>
)
}
Output:
How to Redirect in Next.js ?
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. In this article, we will learn about How to Redirect in NextJS with different approaches.
We will discuss different approaches to Redirect in NextJS:
Table of Content
- Using Redirect method
- Using Configuration setting
- Using Router Push method
- Using Next Response
Contact Us