Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to route to or navigate to a route programmatically in nextjs class component?

I am building a simple app using nextjs. most of my components are functional components. However, I have a class component to handle form.

I want to redirect to the home page after the form is submitted. console.log(this.router) gives undefined. Since it is a class component I can't use useRouter() hook. How do I get reference to router in class components in next.js?

like image 521
mayank1513 Avatar asked Dec 02 '25 06:12

mayank1513


1 Answers

Finally I got the answer,

import Router from 'next/router'

and use Router.push(...)

With Next 13 onwards, import router from next/navigation

like image 155
mayank1513 Avatar answered Dec 03 '25 20:12

mayank1513



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!