Setting a Path
To set a path in Next.js, you typically define routes using the Next.js router. You can define routes using the Link component or by programmatically navigating using the router.
Using the Link Component
The Link component is used to navigate between pages in the Next.js application. Here’s how you can use it:
import Link from 'next/link';
const MyComponent = () => {
return (
<div>
<Link href="/about">
<a>About</a>
</Link>
</div>
);
};
export default MyComponent;
In this example, clicking the “About” link will navigate the user to the /about page.
Programmatically Redirecting
we can also programmatically redirect users using the Next.js router. For example:
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
const MyComponent = () => {
const router = useRouter();
useEffect(() => {
// Redirect to the /about page after 3 seconds
const redirectTimer = setTimeout(() => {
router.push('/about');
}, 3000);
return () => clearTimeout(redirectTimer);
}, []);
return (
<div>
<p>Redirecting to the About page...</p>
</div>
);
};
export default MyComponent;
In this example, the component redirects to the /about page after 3 seconds using the router.push method.