Tuesday, 29 April 2025

Build a Simple To-Do App with Next.js

 

Step 1: Create the Project

Open your terminal and run:

npx create-next-app@latest nextjs-todo --app --ts
cd nextjs-todo
npm install

When prompted, choose:

  • App Router: Yes

  • Tailwind CSS: Yes

  • TypeScript: Yes


Step 2: Clean Starter Files

Open the project and delete the content of app/page.tsx.


Step 3: Add the To-Do App Code

Replace app/page.tsx with the following code:

'use client';

import { useEffect, useState } from 'react';

export default function Home() {
  const [tasks, setTasks] = useState<string[]>([]);
  const [input, setInput] = useState('');

  useEffect(() => {
    const saved = localStorage.getItem('tasks');
    if (saved) {
      setTasks(JSON.parse(saved));
    }
  }, []);

  useEffect(() => {
    localStorage.setItem('tasks', JSON.stringify(tasks));
  }, [tasks]);

  const addTask = () => {
    if (input.trim() === '') return;
    setTasks([...tasks, input.trim()]);
    setInput('');
  };

  const removeTask = (index: number) => {
    const newTasks = [...tasks];
    newTasks.splice(index, 1);
    setTasks(newTasks);
  };

  return (
    <main className="min-h-screen flex flex-col items-center justify-center bg-gray-100 p-4">
      <h1 className="text-3xl font-bold mb-6">To-Do List</h1>
      <div className="flex gap-2 mb-4">
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Add a new task..."
          className="px-4 py-2 rounded border border-gray-300 focus:outline-none focus:ring"
        />
        <button
          onClick={addTask}
          className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
        >
          Add
        </button>
      </div>

      <ul className="w-full max-w-md space-y-2">
        {tasks.map((task, index) => (
          <li
            key={index}
            className="flex justify-between items-center bg-white px-4 py-2 rounded shadow"
          >
            <span>{task}</span>
            <button
              onClick={() => removeTask(index)}
              className="text-red-500 hover:text-red-700"
            >
              ✕
            </button>
          </li>
        ))}
      </ul>
    </main>
  );
}

Step 4: Confirm Tailwind CSS Setup

Your tailwind.config.ts should already include:

content: [
  './app/**/*.{js,ts,jsx,tsx}',
]

No further changes are needed if you selected Tailwind during setup.


Step 5: Run the App

Run the development server:

npm run dev

Then open your browser at:

http://localhost:3000

The app lets you:

  • Add new tasks

  • Delete tasks

  • Save tasks in local storage (they stay after refresh)

  • Use a clean and responsive UI with Tailwind CSS

Sunday, 13 April 2025

Angular Mini Blog App – Beginner Class Task

 

 Step 1: Create a New Angular App

bash

ng new blog-app cd blog-app

Choose CSS and say No to Angular routing when prompted.


 Step 2: Generate Components

bash

ng generate component blog-list ng generate component blog-form

Step 3: Create Blog Model

Create a file named blog.model.ts in the src/app folder:

ts

export interface Blog { id: number; title: string; content: string; author: string; date: string; }

Step 4: Create Blog Service

bash

ng generate service blog

Update blog.service.ts:

ts

import { Injectable } from '@angular/core'; import { Blog } from './blog.model'; @Injectable({ providedIn: 'root' }) export class BlogService { private blogs: Blog[] = [ { id: 1, title: 'Welcome to the Blog!', content: 'This is the first blog post.', author: 'Admin', date: new Date().toLocaleDateString() } ]; getBlogs(): Blog[] { return this.blogs; } addBlog(blog: Blog) { blog.id = this.blogs.length + 1; blog.date = new Date().toLocaleDateString(); this.blogs.push(blog); } }

📄 Step 5: Blog List Component

blog-list.component.ts:

ts

import { Component, OnInit } from '@angular/core'; import { Blog } from '../blog.model'; import { BlogService } from '../blog.service'; @Component({ selector: 'app-blog-list', templateUrl: './blog-list.component.html' }) export class BlogListComponent implements OnInit { blogs: Blog[] = []; constructor(private blogService: BlogService) {} ngOnInit(): void { this.blogs = this.blogService.getBlogs(); } }

blog-list.component.html:

html

<h2>Blog Posts</h2> <div *ngFor="let blog of blogs"> <h3>{{ blog.title }}</h3> <p>{{ blog.content }}</p> <small>By {{ blog.author }} on {{ blog.date }}</small> <hr> </div>

✍️ Step 6: Blog Form Component

blog-form.component.ts:

ts

import { Component } from '@angular/core'; import { BlogService } from '../blog.service'; import { Blog } from '../blog.model'; @Component({ selector: 'app-blog-form', templateUrl: './blog-form.component.html' }) export class BlogFormComponent { newBlog: Blog = { id: 0, title: '', content: '', author: '', date: '' }; constructor(private blogService: BlogService) {} addBlog() { this.blogService.addBlog({ ...this.newBlog }); this.newBlog = { id: 0, title: '', content: '', author: '', date: '' }; } }

blog-form.component.html:

html

<h2>Add New Blog Post</h2> <form (ngSubmit)="addBlog()"> <input [(ngModel)]="newBlog.title" name="title" placeholder="Title" required><br><br> <textarea [(ngModel)]="newBlog.content" name="content" placeholder="Content" required></textarea><br><br> <input [(ngModel)]="newBlog.author" name="author" placeholder="Author" required><br><br> <button type="submit">Add Blog</button> </form>

Step 7: Enable FormsModule

In app.module.ts, import FormsModule:

ts

import { FormsModule } from '@angular/forms';

Add it to the imports array:

ts

imports: [ BrowserModule, FormsModule ]

Step 8: Update app.component.html

html

<app-blog-form></app-blog-form> <hr> <app-blog-list></app-blog-list>

Run Your App

bash

ng serve

Open in your browser: http://localhost:4200