|
| 1 | +--- |
| 2 | +id: pages |
| 3 | +title: Next.js Features - Page |
| 4 | +sidebar_label: Next.js Features - Page |
| 5 | +sidebar_position: 1 |
| 6 | +tags: [Next.js Features ] |
| 7 | +description: "In this section, you will learn about Features of NEXT ." |
| 8 | +--- |
| 9 | + |
| 10 | + |
| 11 | +## Next.js - Pages |
| 12 | + |
| 13 | + |
| 14 | +In Next.js, we can create pages and navigate between them using file system routing feature. We'll use Link component to have a client side navigation between pages. |
| 15 | + |
| 16 | +In Next.js, a page is a React Component and are exported from pages directory. Each page is associated with a route based on its file name. For example |
| 17 | + |
| 18 | +- pages/index.js is linked with '/' route. |
| 19 | + |
| 20 | +- pages/posts/first.js is linked with '/posts/first' route and so on. |
| 21 | + |
| 22 | +Let's update the nextjs project created in Environment Setup chapter. |
| 23 | + |
| 24 | +Create post directory and first.js within it with following contents. |
| 25 | + |
| 26 | +``` |
| 27 | +export default function FirstPost() { |
| 28 | + return <h1>My First Post</h1> |
| 29 | +} |
| 30 | +``` |
| 31 | +Add Link Support to go back to Home page. Update first.js as follows − |
| 32 | + |
| 33 | +``` |
| 34 | +import Link from 'next/link' |
| 35 | +
|
| 36 | +export default function FirstPost() { |
| 37 | + return ( |
| 38 | + <> |
| 39 | + <h1>My First Post</h1> |
| 40 | + <h2> |
| 41 | + <Link href="/"> |
| 42 | + <a>Home</a> |
| 43 | + </Link> |
| 44 | + </h2> |
| 45 | + </> |
| 46 | + ) |
| 47 | +} |
| 48 | +``` |
| 49 | +Add Link Support to home page to navigate to first page. Update index.js as follows − |
| 50 | + |
| 51 | +``` |
| 52 | +import Link from 'next/link' |
| 53 | +
|
| 54 | +function HomePage() { |
| 55 | + return ( |
| 56 | + <> |
| 57 | + <div>Welcome to Next.js!</div> |
| 58 | + <Link href="/posts/first"><a>First Post</a></Link> |
| 59 | + </> |
| 60 | + ) |
| 61 | +} |
| 62 | +
|
| 63 | +export default HomePage |
| 64 | +``` |
| 65 | + |
| 66 | +## Start Next.js Server |
| 67 | + |
| 68 | +Run the following command to start the server −. |
| 69 | +``` |
| 70 | +npm run dev |
| 71 | +> [email protected] dev \Node\nextjs |
| 72 | +> next |
| 73 | +
|
| 74 | +ready - started server on http://localhost:3000 |
| 75 | +event - compiled successfully |
| 76 | +event - build page: / |
| 77 | +wait - compiling... |
| 78 | +event - compiled successfully |
| 79 | +event - build page: /next/dist/pages/_error |
| 80 | +wait - compiling... |
| 81 | +event - compiled successfully |
| 82 | +``` |
| 83 | + |
| 84 | +## Verify Output |
| 85 | + |
| 86 | +Open localhost:3000 in a browser and you will see the following output. |
| 87 | +``` |
| 88 | +Home page |
| 89 | +``` |
| 90 | +Click on First Link and you will see the following output. |
0 commit comments