The standard approach to enable client-side navigation with the <a> tag in Next.js is to use the Link component provided by Next.js. This component, sourced from the next/link module, enables client-side routing where only specific parts of the page are rendered.
Here's an example using Link:
jsximport Link from 'next/link'; const Navigation = () => { return ( <nav> <ul> <li> <Link href="/"> <a>Home</a> </Link> </li> <li> <Link href="/about"> <a>About Us</a> </Link> </li> <li> <Link href="/contact"> <a>Contact</a> </Link> </li> </ul> </nav> ); }; export default Navigation;
With this approach, Next.js handles navigation on the client side without making server requests to fetch new pages. This not only improves page load speed but also enhances user experience.
It's important to note that the href attribute of the Link component is required, as it specifies the route path. If you need to add additional logic on click, such as recording analytics events, you can simply add an onClick event handler to the <a> tag.
For custom attributes like title, className, or data-* that are unrelated to routing, you can add them directly to the <a> tag, and the Link component will propagate them to the underlying <a> element.
Finally, for programmatic navigation, such as navigating to a new page after form submission, you can use Next.js's useRouter or withRouter hooks. These APIs enable navigation without relying on the <a> tag.
Here's an example:
jsximport { useRouter } from 'next/router'; const FormComponent = () => { const router = useRouter(); const handleSubmit = async (event) => { event.preventDefault(); // Handle form data logic... // Navigate to new page after form processing router.push('/thank-you'); }; return ( <form onSubmit={handleSubmit}> {/* Form elements */} <button type="submit">Submit</button> </form> ); }; export default FormComponent;
In this example, when the form is submitted, the handleSubmit function is triggered, and after processing the necessary logic, it navigates to the /thank-you page using router.push. This provides a seamless user experience similar to clicking the <a> tag.