Solution: Routing
Explore how to implement effective routing in Next.js by creating a Header component with navigation links and using the next/router for page transitions. Understand how to manage routing across different pages to build smooth and user-friendly Jamstack applications.
We'll cover the following...
Solution
First, let's take a look at the code below to see how to complete this challenge, and then we'll discuss it for a better understanding.
import React from 'react'
import styles from '../styles/Home.module.css'
import Link from 'next/link';
import { useRouter } from 'next/router';
const Header = () => {
const router = useRouter();
const handleHome = () => {
router.push('/dynamic/1')
}
return (
<>
<div className={styles.container}>
<div onClick={handleHome}>
Home
</div>
<div className={styles.linkContainer}>
<div className={styles.link} >
<Link href='/page1'>Page 1</Link>
</div>
<div className={styles.link}>
<Link href='/dynamic/1'>Dymanic 1</Link>
</div>
<div className={styles.link}>
<Link href='/dynamic/2'>Dymanic 2</Link>
</div>
</div>
</div>
</>
)
}
export default Header;Solution explanation
Let's take a look at this solution's explanation:
/components/Header.js: We create aHeadercomponent with four links. We useLink href='<path>'>to route to the specific page. Additionally, we use thenext/routercomponent to route to the/pages/index.jspage, just so we can get hands-on experience./pages/index.js: We import theHeader.jsfile and use it to display theHeadercomponent. The same thing is done for the rest of the files in the/pagesdirectory.
Note: The second step has to be done in all files in the
/pagesdirectory except for the_app.jsfile.