# Session 6: WebApp - Frontend (Next.js)
## Overview
Welcome to Session 6! In this session, we'll focus on building the frontend of our web application using Next.js, a powerful React framework. Next.js provides features like server-side rendering, static site generation, and simplified routing that make it an excellent choice for modern web applications.
## Learning Objectives
- Understand what Next.js is and its advantages
- Set up a Next.js project
- Learn React fundamentals
- Create responsive layouts with Tailwind CSS
- Build reusable components
- Implement client-side routing
- Fetch data from APIs
## Topics Covered
### 1. Introduction to Next.js
Next.js is a React framework that provides structure, features, and optimizations for your application.
#### Key Features:
- **Server-Side Rendering (SSR)**: Renders pages on the server for better SEO and performance
- **Static Site Generation (SSG)**: Pre-renders pages at build time for faster load times
- **File-based Routing**: Creates routes based on your file structure
- **API Routes**: Allows you to build API endpoints as part of your Next.js app
- **Automatic Code Splitting**: Loads only the code needed for each page
- **Built-in CSS and Sass Support**: Allows importing CSS/Sass files directly
- **Fast Refresh**: Preserves component state during development
### 2. Setting Up a Next.js Project
```bash
# Create a new Next.js app
npx create-next-app my-todo-app
cd my-todo-app
# Start the development server
npm run dev
```
#### Project Structure:
```
my-todo-app/
├── node_modules/
├── public/ # Static assets
├── src/
│ ├── app/ # App router pages and layouts
│ │ ├── page.js # Home page (/route)
│ │ └── layout.js # Root layout
│ ├── components/ # Reusable components
│ └── styles/ # CSS files
├── .eslintrc.json
├── next.config.js # Next.js configuration
├── package.json # Project dependencies
└── README.md
```
### 3. React Fundamentals
Next.js is built on top of React, so understanding React fundamentals is essential.
#### Components
Components are the building blocks of React applications. They are reusable pieces of code that return HTML elements.
```jsx
// Simple functional component
function Greeting({ name }) {
return
Hello, {name}!
;
}
// Using the component
```
#### Props
Props (short for properties) are how you pass data to components.
```jsx
function TodoItem({ task, completed, onToggle }) {
return (
{task}
);
}
```
#### Hooks
Hooks are functions that let you "hook into" React state and lifecycle features.
```jsx
import { useState, useEffect } from 'react';
function TodoList() {
// State hook for managing tasks
const [tasks, setTasks] = useState([]);
const [newTask, setNewTask] = useState('');
// Effect hook for fetching tasks
useEffect(() => {
// Fetch tasks from API
fetch('/api/tasks')
.then(response => response.json())
.then(data => setTasks(data));
}, []); // Empty dependency array means this runs once when component mounts
// Function to add a new task
const addTask = () => {
if (newTask.trim()) {
setTasks([...tasks, { id: Date.now(), text: newTask, completed: false }]);
setNewTask('');
}
};
return (
Todo List
setNewTask(e.target.value)}
placeholder="Add a new task"
/>
);
}
export default TaskList;
```
### 7. Building Our Todo App Frontend
Let's structure our Todo app frontend:
1. **Components**:
- `TaskList`: Displays all tasks
- `TaskItem`: Individual task with toggle and delete functionality
- `TaskForm`: Form for adding new tasks
- `Layout`: Common layout for all pages
2. **Pages**:
- Home: Landing page
- Tasks: List of all tasks
- Task Detail: View/edit a specific task
Here's a sample implementation of the `TaskItem` component using Tailwind CSS:
```jsx
'use client';
function TaskItem({ task, onToggleComplete, onDelete }) {
return (
);
}
export default TaskItem;
```
## Practice Exercises
1. Set up a new Next.js project with Tailwind CSS
2. Create a simple landing page with a navigation menu
3. Build a task list page that displays mock tasks
4. Create a form to add new tasks to the list
5. Implement client-side form validation
6. Add the ability to mark tasks as complete and delete tasks
## Additional Resources
- [Next.js Documentation](https://nextjs.org/docs)
- [React Documentation](https://reactjs.org/docs/getting-started.html)
- [Tailwind CSS Documentation](https://tailwindcss.com/docs)
- [React Hooks Reference](https://reactjs.org/docs/hooks-reference.html)
- [Next.js GitHub Examples](https://github.com/vercel/next.js/tree/canary/examples)
## Next Steps
Now that you've learned how to build the frontend of a web application with Next.js, you're ready to move on to [Session 7: WebApp - Backend](Session-7-WebApp-Backend.md) where you'll learn how to create a backend API using Django Ninja.