Module 2: Core Concepts in Next.js

Module 2: Core Concepts in Next.js

Topic 1: Pages and Routing

Overview

This section delves into Next.js’s powerful page and routing features. We will explore creating pages, linking between them, and leveraging dynamic routing to build sophisticated applications.


- Creating Pages: How to create pages by adding files in the pages directory.

- Linking Pages: Navigating between pages using the Link component.

- Dynamic Routing: Creating dynamic routes with file-based routing.

- Nested Routes: Organizing your application with nested routes.

- API Routes: Introduction to setting up API endpoints within the pages/api directory.


Code Examples

Creating Pages

Create a new file pages/about.js:

```jsx        
// pages/about.js        
const About = () => {        
  return <h1>About Page</h1>;        
};        
export default About;        
```        


Linking Pages

Use the Link component to navigate between pages:

```jsx        
// pages/index.js        
import Link from 'next/link';        
const Home = () => {        
  return (        
    <div>        
      <h1>Home Page</h1>        
      <Link href="/about">        
        <a>Go to About Page</a>        
      </Link>        
    </div>        
  );        
};        
export default Home;        
```        


Dynamic Routing

Create a dynamic route by using brackets in the file name:

```jsx        
// pages/post/[id].js        
import { useRouter } from 'next/router';        
const Post = () => {        
  const router = useRouter();        
  const { id } = router.query;        
  return <h1>Post ID: {id}</h1>;        
};        
export default Post;        
```        




Topic 2: Static Generation (SSG) and Server-Side Rendering (SSR)

Overview

In this section, we'll cover the core concepts of static generation and server-side rendering in Next.js, explaining how and when to use each approach.

- Static Generation (SSG): Generate static HTML at build time.

- Server-Side Rendering (SSR): Generate HTML on each request.

- Incremental Static Regeneration (ISR): Update static content after the build.

- Choosing Between SSG and SSR: Understand when to use each method.


Code Examples

Static Generation (SSG)

Use getStaticProps to fetch data at build time:

```jsx        
// pages/blog.js        
export async function getStaticProps() {        
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');        
  const posts = await res.json();        
  return {        
    props: {        
      posts,        
    },        
  };        
}        
const Blog = ({ posts }) => {        
  return (        
    <div>        
      <h1>Blog</h1>        
      <ul>        
        {posts.map(post => (        
          <li key={post.id}>{post.title}</li>        
        ))}        
      </ul>        
    </div>        
  );        
};        
export default Blog;        
```        


Server-Side Rendering (SSR)

Use getServerSideProps to fetch data on each request:

```jsx        
// pages/user.js        
export async function getServerSideProps() {        
  const res = await fetch('https://jsonplaceholder.typicode.com/users');        
  const users = await res.json();        
  return {        
    props: {        
      users,        
    },        
  };        
}        
const User = ({ users }) => {        
  return (        
    <div>        
      <h1>Users</h1>        
      <ul>        
        {users.map(user => (        
          <li key={user.id}>{user.name}</li>        
        ))}        
      </ul>        
    </div>        
  );        
};        
export default User;        
```        





Topic 3: API Routes

Overview

Learn how to create backend API routes directly within your Next.js application. This section covers the basics of creating, organizing, and using API routes.

- Creating API Routes: Set up API routes using the pages/api directory.

- Handling Requests: Different methods for handling GET, POST, PUT, and DELETE requests.

- Connecting to a Database: Example of connecting API routes to a database.

- API Route Best Practices: Tips for structuring and securing your API routes.


Code Examples

Creating API Routes

Create a simple API route in pages/api/hello.js:

```jsx        
// pages/api/hello.js        
export default function handler(req, res) {        
  res.status(200).json({ message: 'Hello, world!' });        
}        
```        


Handling Different Requests

Handle different HTTP methods in an API route:

```jsx        
// pages/api/user.js        
export default function handler(req, res) {        
  const { method } = req;        
  switch (method) {        
    case 'GET':        
      // Handle GET request        
      res.status(200).json({ message: 'GET request' });        
      break;        
    case 'POST':        
      // Handle POST request        
      res.status(200).json({ message: 'POST request' });        
      break;        
    default:        
      res.setHeader('Allow', ['GET', 'POST']);        
      res.status(405).end(`Method ${method} Not Allowed`);        
  }        
}        
```        




Topic 4: Data Fetching

Overview

This section explores the various data fetching methods available in Next.js, including static generation, server-side rendering, and client-side fetching.

- Static Generation with getStaticProps: Fetch data at build time.

- Server-Side Rendering with getServerSideProps: Fetch data on each request.

- Client-Side Fetching: Fetch data on the client side using useEffect.

- Combining Methods: Examples of combining different data fetching strategies.


Code Examples

Static Generation with getStaticProps

```jsx        
// pages/products.js        
export async function getStaticProps() {        
  const res = await fetch('https://api.example.com/products');        
  const products = await res.json();        
  return {        
    props: {        
      products,        
    },        
  };        
}        
const Products = ({ products }) => {        
  return (        
    <div>        
      <h1>Products</h1>        
      <ul>        
        {products.map(product => (        
          <li key={product.id}>{product.name}</li>        
        ))}        
      </ul>        
    </div>        
  );        
};        
export default Products;        
```        


Server-Side Rendering with getServerSideProps

```jsx        
// pages/orders.js        
export async function getServerSideProps() {        
  const res = await fetch('https://api.example.com/orders');        
  const orders = await res.json();        
  return {        
    props: {        
      orders,        
    },        
  };        
}        
const Orders = ({ orders }) => {        
  return (        
    <div>        
      <h1>Orders</h1>        
      <ul>        
        {orders.map(order => (        
          <li key={order.id}>{order.item}</li>        
        ))}        
      </ul>        
    </div>        
  );        
};        
export default Orders;        
```        


Client-Side Fetching with useEffect

```jsx        
// pages/dashboard.js        
import { useState, useEffect } from 'react';        
const Dashboard = () => {        
  const [data, setData] = useState([]);        
  useEffect(() => {        
    async function fetchData() {        
      const res = await fetch('https://api.example.com/dashboard');        
      const result = await res.json();        
      setData(result);        
    }        
    fetchData();        
  }, []);        
  return (        
    <div>        
      <h1>Dashboard</h1>        
      <ul>        
        {data.map(item => (        
          <li key={item.id}>{item.name}</li>        
        ))}        
      </ul>        
    </div>        
  );        
};        
export default Dashboard;        
```        


By mastering these topics, you'll be well-equipped to build powerful, data-driven applications with Next.js.

Pradeepan Ganesh R.

People & Administrative Operations

2 个月
回复
Aashish Bhagwat

Angular, React, NodeJs, Ionic, Laravel, Tailwind ???

2 个月

Hello everyone! ?? I'm Aashish, a full-stack developer with over 7 years of experience. My expertise lies in Angular, Node.js, ReactJS, Laravel, IONIC, and Tailwind.I'd love to connect with fellow developers. Let's discuss innovative projects, share technical insights, and explore the latest web development trends.?? Let's collaborate! Contact me at:+91-8208690072 (call)+91-9403733265 (WhatsApp)Portfolio: https://aashish-bhagwat.creativehand.co.inEmail: [email protected]

回复

要查看或添加评论,请登录

Pradeep Misra的更多文章