Solution: Routing
Let's discuss the solution to the Routing challenge.
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 aHeader
component with four links. We useLink href='<path>'>
to route to the specific page. Additionally, we use thenext/router
component to route to the/pages/index.js
page, just so we can get hands-on experience./pages/index.js
: We import theHeader.js
file and use it to display theHeader
component. The same thing is done for the rest of the files in the/pages
directory.
Note: The second step has to be done in all files in the
/pages
directory except for the_app.js
file.