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 to the challenge

Solution explanation

Let's take a look at this solution's explanation:

  1. /components/Header.js: We create a Header component with four links. We use Link href='<path>'> to route to the specific page. Additionally, we use the next/router component to route to the /pages/index.js page, just so we can get hands-on experience.

  2. /pages/index.js: We import the Header.js file and use it to display the Header 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.