DEV Community

Cover image for Getting Started with React.js and Next.js – A Beginner's Guide to Creating Pages, Routing, and Dynamic Content
sarah
sarah

Posted on

Getting Started with React.js and Next.js – A Beginner's Guide to Creating Pages, Routing, and Dynamic Content

Next.js is a powerful and popular framework for building server-side rendered React applications. With Next.js you do not need to install any fancy dependency to handle routes, Next.js provides a built-in routing system that makes it easy to navigate between pages.

In this article, we'll explore the basics of creating pages with Next.js and React.js, including routing and dynamic content. If you want to learn how to add Next.js to your project, I wrote an article about Getting started with Next.js you can check out.

Creating Pages with Next.js and React.js


Creating pages in your react app has been made easy with Next.js. When you install Next.js in your project, you will notice a pages directory that next.js has already created for you.

Inside this directory, you will also notice some default files and folders – app directory, index.js, _app.js, and _document.js. “index.js” is your root homepage, while _app.js is your root App. The index.js would have some code in it, edit it as is appropriate to your project. When Next.js sees an index page in your file, it will create a root path for that file.

You can create other pages like “about.js” and “contact.js” inside the pages directory and then add your react code like this:

const MyPage = () => {
  return (
    <div>Hello World!</div>
  )
}

export default MyPage

Enter fullscreen mode Exit fullscreen mode

In the code example above, we have created a myPage component function that returns a div with a content of “Hello World!”.

To check if your code works, test it on http://localhost:3000/

Using Next.js Link Component


Next.js provides a built-in routing system that makes it easy to navigate between pages. To create a link to another page, use the Link component from the next/link module.

The Link component is an amazing feature in next.js, it enables client-side navigation which allows users to navigate between pages without a full page reload. This enhances the user experience by providing faster transitions and preserving the application state.

For example, to create a link to the about page, you would use the following code:

import Link from 'next/link';

function MyPage() {
  return (
    <div>
      <h1>Welcome to my website</h1>
      <Link key=”1” href="/about" passHref>
        <a>About</a>
      </Link>
    </div>
  );
}

export default MyPage;
Enter fullscreen mode Exit fullscreen mode

In the code example above, the link component was first imported from the next/link module. After importing the Link component, you should be able to use it in your code.

The passHref prop in the Link component of Next.js is used to pass the href attribute to the underlying anchor (a) tag. passHref is used for accessibility and seo, when using third-party libraries or working with complex DOM interactions.

Your Link component jsx should always have a KEY (key={data.id}). You can learn more about keys in the article -- rendering lists

Routing file system in Next.js


In Next.js, you can create dynamic pages with dynamic paths that include IDs. You do not need an extra library to help manage your pages. Next.js identifies dynamic files by adding square brackets [ ] around the file name.

Next.js creates dynamic pages with dynamic paths that include IDs by using the getStaticPaths and getStaticProps functions. getStaticPaths and getStaticProps are used to tell Next.js what page and path to generate. For dynamic pages you need both, but for static pages you only need getStaticProps. getStaticPaths is used to specify the exact path (url).

Here's an example of how to create dynamic pages with IDs in Next.js:

Create a page component in the pages directory, and include [id] as the filename to indicate that it is a dynamic page. For example, pages/posts/[id].js, inside the page, add the code below

const Post = ( {data} ) => {

    return (
        <div>
            <Image src={data.image} width={500} height={300} alt={data.title}/>
            <h1>{data.title}</h1>
            <p>{data.description}</p>
        </div>
    )
}

export default Post;
Enter fullscreen mode Exit fullscreen mode

Define the getStaticPaths function in the same component. This function is used to generate all the possible paths for this page at build time. For example:

export async function getStaticPaths() {
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();

  const paths = posts.map(post => ({
    params: { id: post.id.toString() },
  }));

  return { paths, fallback: false };
}
Enter fullscreen mode Exit fullscreen mode

In this example, we fetch all the posts from an API and map them to an array of paths with the id parameter included. The fallback property is set to false, which means that any path not included in the paths array will result in a 404 page.

Define the getStaticProps function to fetch the data for the individual post with the given id. This function is called at build time for each path generated by getStaticPaths. For example:

export async function getStaticProps({ params }) {
  const res = await fetch(`https://api.example.com/posts/${params.id}`);
  const post = await res.json();

  return { props: { post } };
}
Enter fullscreen mode Exit fullscreen mode

In this example, we fetch the individual post data using the params.id value from the URL path, and return it as a prop to the component.

Remember to define getStaticPaths or getStaticProps after you have defined your component, not before or inside the component.

That's it! Now you can use this dynamic page component to display individual posts based on their IDs. To test, add the url path plus any letter or number.

When a user navigates to a URL like /post/123, Next.js will automatically generate the static HTML and JSON files for that page at build time, and serve them to the user at runtime.

Conclusion


We've successfully explored the basics of creating pages with Next.js and React.js, including routing and dynamic content.

Hopefully with these tools, you can begin to create powerful and performant web applications with Next.js and React.js that offer a great user experience.

Happy coding!

Top comments (0)