FE-302 PPT Notes
FE-302 PPT Notes
● Utility Classes
○ Utility Classes:
■ Represent specific CSS properties and allow for direct styling within
HTML.
■ Example:
<div class="text-center font-bold p-4">your content
here</div>
■ Equivalent to Vanilla CSS:
.text-center { text-align: center; }
.font-bold { font-weight: bold; }
.p-4 { padding: 1rem; } /* 16px */
○ Types of Utility Classes:
■ Typography Utility Classes: For text styling.
■ Spacing Utility Classes: For margin and padding.
■ Sizing Utility Classes: For height and width.
■ Border Utility Classes: For border properties.
○ 1. Typography Utility Classes :
■ Example:
● Tailwind:
<p class="text-xl font-semibold">This is
extra-large, semi-bold text.</p>
● Vanilla CSS
.text-xl { font-size: 1.25rem; }
.font-semibold { font-weight: 600; }
■ Demo: Using Tailwind Typography utility classes:
● Add large text, bold weight, and center-aligned styles.
● Example:
<p class="text-xl">This is a large text.</p>
<p class="font-bold">This text is bold.</p>
<p class="text-center">This text is centered.</p>
■ Debrief: After adding the typography utility classes, the text will
display as large, bold, and center-aligned.
○ 2. Spacing Utility Classes:
■ Control spacing (margin and padding) with units based on a scale:
● 1 unit = 0.25rem (4px), 2 units = 0.5rem (8px), 4 units = 1rem
(16px), etc.
■ Example:
● Tailwind:
<div class="p-6 mt-3">Your content here</div>
● Equivalent Vanilla CSS
div { padding: 1.5rem; margin-top: 0.75rem; }
■ Demo:
● Use utility classes for different padding and margin
configurations (e.g., p-4, m-2, pl-8, mb-8).
○ 3. Sizing Utility Classes:
■ Set element sizes such as height and width.
■ Fractional Widths: w-1/2, w-1/3, etc., for relative widths.
■ Fixed Heights: h-24 corresponds to a height of 6rem.
■ Example:
● Tailwind:
<div class="w-1/2 h-24">Your content here</div>
● Equivalent Vanilla CSS:
div { width: 50%; height: 6rem; }
■ Demo:
● Use utility classes like w-1/2, h-24 for widths and heights
with background color adjustments.
■ Debrief:
● Spacing and sizing utility classes allow quick adjustments
without writing custom CSS, ensuring consistency and ease of
use.
○ 4. Border Utility Classes:
● Used to style elements' borders.
● Example:
○ Tailwind:
<div class="border-2 rounded-lg">Your content
here</div>
○ Equivalent Vanilla CSS:
div { border: 2px solid; border-radius: 0.5rem;
}
■ Debrief:
● Tailwind's responsive utilities allow easy and dynamic
adjustments for different screen sizes, making it a powerful tool
for mobile-first and adaptive designs.
● Adding Hover Effects with Tailwind CSS
○ Hover Effect Demo:
■ Starter Code:
● Create a button with basic styling:
<button class="bg-blue-500 text-white px-4
py-2 rounded">Click Me</button>
○ Hover Effect with Tailwind:
■ Updated Code:
● Add a hover effect to change the button's background
color:
<div>
<button class="bg-blue-500 text-white
px-4 py-2 rounded hover:bg-blue-700">Click
Me</button>
<p class="text-gray-700">This text
changes color when the button is
hovered.</p>
</div>
■ The hover:bg-blue-700 class changes the button’s
background color when hovered.
○ Debrief:
■ Tailwind allows easy hover effects using the hover: prefix,
making it quick to add interactive styles.
● Flexbox, Grid, and Responsive Layouts with Tailwind CSS
○ Flexbox Utility Classes:
■ Tailwind provides utility classes for Flexbox properties (flex,
justify-content, align-items).
■ Example:
<div class="flex justify-between items-center">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
○ Flexbox Demo:
■ Goal: Create a responsive pricing card layout that adapts from
a single-column on small screens to a two-column layout on
medium screens using Flexbox.
○ Responsive Navbar Activity:
■ Objective: Build a responsive navbar with a logo and menu
items. Use Tailwind to add hover effects and adapt the layout
for mobile and larger screens.
○ Grid Utility Classes:
■ Tailwind includes utility classes for grid properties
(grid-cols, gap, grid-rows).
■ Example:
<div class="grid grid-cols-3 gap-4">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
■
○ Grid Layout Demo:
■ Task: Implement a grid that has two columns on small screens
and expands to four columns on larger screens, with uniform
gaps and padding around the grid container.
○ Grid Gallery Activity:
■ Objective: Design a grid gallery with images, where:
● Images stack in one column on mobile screens.
● Transitions to 2-column on small screens and 3-column
on medium screens.
● Adds hover effects to change image opacity.
● Installing and Configuring Tailwind CSS
○ Demo: Install Tailwind CSS
■ Fork Code Sandbox: Track default styles.
■ Install Tailwind CSS:
● npm install -D tailwindcss
■ Initialize Tailwind Config:
● npx tailwindcss init
■ Update tailwind.config.js:
module.exports = {
content: ["./src/**/*.{html,js}"],
// other configurations
};
■ Add Tailwind Directives to styles.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
■ Start Tailwind Build Process:
npx tailwindcss -i ./src/styles.css -o
./output.css --watch
■ Include the Output File in index.html:
<link rel="stylesheet" href="./output.css">
■ Check if Default Styles Changed: Verify if base styles have
been reset.
○ Understanding Base Styles
■ Purpose: Ensure consistent appearance across different
browsers and reset browser inconsistencies.
○ Demo: Modifying tailwind.config.js
■ Add Custom Font Family:
module.exports = {
theme: {
extend: {
fontFamily: {
display: ['Pally', 'Comic Sans MS',
'sans-serif'],
body: ['Pally', 'Comic Sans MS',
'sans-serif'],
},
},
},
// other configurations
};
■ Apply Custom Font in App.js:
● For h1: Use class="font-display"
● For p: Use class="font-body"
■ Ensure Fonts Update: Verify that the fonts have been applied
correctly.
○ Benefits:
■ Cleaner and more flexible code.
■ Supports query parameters and dynamic link creation.
● Retrieving Route and Query Parameters
○ Using useParams Hook:
import { useParams } from 'next/navigation';
export default function ProductPage() {
const params = useParams();
const pageId = params.pageId;
return <h1>Product Page: {pageId}</h1>;
}
○
○ Using useSearchParams Hook:
import { useSearchParams } from 'next/navigation';
export default function Page() {
const searchParams = useSearchParams();
const category = searchParams.get('category');
const sort = searchParams.get('sort');
return (
<div>
<p>Category: {category}</p>
<p>Sort: {sort}</p>
</div>
);
}
○
○ Key Points:
■ useParams(): Retrieves route parameters.
■ useSearchParams(): Retrieves query parameters.
■ Simplifies access to URL data.
● Navigating Programmatically with useRouter Hook
○ Example Usage:
import { useRouter } from 'next/navigation';
export default function AboutPage() {
const router = useRouter();
function handleNavigate() {
router.push('/about');
}
return <button onClick={handleNavigate}>Go to About
Page</button>;
}
○
○ Key Methods:
■ router.push('/path'): Navigate to a specific route.
■ router.back(): Go back to the previous page.
■ router.replace('/path'): Navigate to a route without adding to
history stack.
○ Difference between router.push() and router.replace():
■ router.push(): Adds new route to history, allows navigating back.
■ router.replace(): Replaces the current route in history, prevents
navigating back.
● Activities
○ Create Pages and Implement Navigation:
■ Implement pages (/, /page1, /page2).
■ Use router.push() and router.replace() to navigate and
observe differences.
○ Using useRouter:
■ Create an "About" page and navigate programmatically from the home
page using buttons.
● Conclusion
○ Understanding Routing: Importance of client-side vs. server-side routing,
and the benefits of Next.js’s navigation methods.
○ Practical Application: Implementing and using routing methods effectively in
Next.js applications.
12 Sep 2024 - Session 5
Data Fetching
● Agenda Overview
○ Data Fetching (Client Side vs Server Side)
○ Static Site Generation using generateStaticParams
○ Data Caching
○ Data Revalidation
● Detailed Breakdown
○ 1. Data Fetching (Client Side vs Server Side)
■ Scenario 1 (Client-Side Fetching):
● The librarian fetches the book when a visitor asks. This is
analogous to client-side fetching where data is loaded
dynamically on each request, often resulting in longer wait
times and multiple server requests.
● Activity: Demonstrate client-side data fetching using React
hooks like useEffect and useState.
■ Scenario 2 (Server-Side Fetching):
● The librarian prepares popular books in advance for visitors.
This is analogous to server-side rendering (SSR) where data is
fetched and rendered on the server, resulting in faster initial
page loads.
● Activity: Demonstrate server-side data fetching using
server-side functions.
○ 2. Static Site Generation (SSG) using generateStaticParams
■ Scenario: Pages are pre-generated at build time, so when a visitor
requests a page, it’s served quickly without additional server requests.
● Activity: Implement generateStaticParams to pre-render
pages at build time, reducing server load and improving load
times.
■ Code:
export async function generateStaticParams() {
const posts = await
fetch('https://jsonplaceholder.typicode.com/posts').th
en(res => res.json());
return posts.map(post => ({ id: post.id.toString()
}));
}
●
■ Debrief: SSG improves performance by pre-rendering pages and
reducing server load during requests.
○ 3. Data Caching
■ Activity: Demonstrate caching by changing cache settings and
observing effects on data fetching and loading times.
● Code: Change cache settings from no-store to
force-cache to see how data retrieval is affected.
● Discussion: Explain how caching improves performance by
storing and reusing previously fetched data, reducing server
load, and speeding up response times.
■ Concepts:
● Request Memoization (In-memory): Temporary caching for
the duration of a request.
● Data Cache (Persistent): Long-term caching across multiple
requests.
○ 4. Data Revalidation
■ Activity: Implement revalidation to update cached data at specific
intervals.
● Code: Add { next: { revalidate: 10 } } to API calls
to revalidate data every 10 seconds.
● Discussion: Revalidation ensures that cached data is updated
periodically, maintaining a balance between performance and
data freshness.
● Activities and Solutions
○ Data Fetching (Server Side)
■ Fetch posts and display them on the homepage.
■ Implement a post page with individual post details.
■ Solution: Fork the provided CodeSandbox links for practical
implementation.
○ Static Site Generation
■ Pre-generate pages during build time and observe the reduced server
load and improved load times.
■ Solution: Build the project and inspect the
.next/server/app/post directory for generated pages.
○ Caching
■ Change caching settings and compare loading times and data
freshness.
■ Solution: Refresh the page and check network requests to observe
caching effects.
○ Data Revalidation
■ Implement revalidation and observe how data updates at specified
intervals.
■ Solution: Modify API calls and refresh to see the impact of
revalidation.
● Final Takeaways
○ Client-Side vs Server-Side Fetching: Client-side fetching is dynamic but
slower, while server-side fetching provides faster initial loads.
○ Static Site Generation: Pre-generates pages at build time, improving
performance and reducing server load.
○ Caching: Improves performance by storing and reusing data, reducing the
need for repeated server requests.
○ Revalidation: Keeps cached data up-to-date while maintaining performance
benefits.
<NextAuthSessionProvider>{children}</NextAuthSessionPr
ovider>
</body>
</html>
);
}
■
○ 7. Update Homepage for Authentication:
■ Modify app/page.js to handle login/logout functionality and display
user info.
○ 8. Create Protected Route:
■ Implement app/protected/page.js:
import { getServerSession } from "next-auth/next";
import { options } from
"../api/auth/[...nextauth]/route";
oimprt { redirect } from "next/navigation";
import Link from "next/link";
export default async function ProtectedPage() {
const session = await getServerSession(options);
if (!session) {
redirect("/api/auth/signin?callbackUrl=/protected");
}
return (
<div>
<h1>Protected Page</h1>
<p>Welcome, {session.user.name}!</p>
<Link href="/">Go to Home</Link>
</div>
);
}
○
● Summary
○ NextAuth Setup:
■ Installed and configured NextAuth with GitHub as the authentication
provider.
■ Set up environment variables and API routes.
■ Implemented session management with SessionProvider.
○ Home Page and Protected Routes:
■ Updated the home page to handle user authentication status.
■ Created a protected route accessible only to authenticated users.
○ Middleware and Access Control:
■ Discussed the basics of implementing middleware for authentication
and access control.
16 Sep 2024 - Session 7
CSS Modules, Global Styles, and Tailwind CSS
● Agenda
○ CSS Modules
○ Global Styles
○ Tailwind CSS
● Activity 1.1: Identify the Issue
○ Task: Identify styling issues in the Card and Alert components.
■ Current View vs. Expected View: The design has color issues.
■ CSS Files: Alert.css and Card.css both contain the same styles.
■ Inspection: Colors are not as expected due to CSS cascading and
specificity issues.
● Debrief:
○ Cascading: In CSS, the last imported stylesheet’s rules override earlier ones
if they have the same specificity.
○ Specificity: If styles have the same specificity, the order of stylesheet imports
determines which styles apply.
● Activity 1.2: Using CSS Modules
○ Rename CSS Files:
■ Change Alert.css to Alert.module.css and Card.css to
Card.module.css.
○ Modify Imports:
■ Import styles as objects in Alert.jsx and Card.jsx.
○ Example:
import styles from './Alert.module.css';
○ Apply Styles:
■ Update the components to use the imported styles object.
○ Verify UI:
■ Check that the styles are now applied correctly and class names are
unique, avoiding collisions.
● Global Styles
○ Usage: Place global styles (e.g., font-family, background color) in
globals.css.
○ Integration: Import globals.css in your main layout or _app.js to apply
styles globally.
○ Note: Media queries and other global styles should be included here as they
don't work well with module-scoped CSS.
● Tailwind CSS
○ Introduction:
■ Utility-First Framework: Build designs using predefined utility
classes.
■ Analogy: Like LEGO blocks, utility classes are used to construct UI
elements quickly.
○ Integration:
■ New Next.js App: Use npx create-next-app@latest
my-tailwind-app and select Tailwind CSS during setup.
■ Existing Next.js App:
○ Install Tailwind CSS and its dependencies:
npm install -D tailwindcss postcss autoprefixer
○ Initialize Tailwind:
npx tailwindcss init -p
○ Update tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx,mdx}",
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {},
},
plugins: [],
}
○ Update global CSS file (app/globals.css):
@tailwind base;
@tailwind components;
@tailwind utilities;
○ Test Integration:
■ Add a Tailwind CSS test component in app/page.jsx to verify setup:
export default function TailwindTest() {
return (
<div className="flex items-center justify-center
min-h-screen bg-teal-600">
<h1 className="text-3xl font-bold text-white
bg-teal-500 p-4 rounded-lg shadow-md">
Tailwind CSS is working!
</h1>
</div>
)
}
Encryption No
Authentication No
Vulnerability Yes