Chapter 16 Exercises: Web Frontend Development with AI
Tier 1: Remember and Understand (Exercises 1-6)
Exercise 1: Frontend Technology Matching
Match each frontend technology with its primary role:
| Technology | Role Options |
|---|---|
| HTML | a) Application logic and interactivity |
| CSS | b) Package management and dependency resolution |
| JavaScript | c) Content structure and semantics |
| React | d) Visual presentation and layout |
| npm | e) Component-based UI framework |
| Tailwind CSS | f) Utility-first styling framework |
Exercise 2: Python-to-JavaScript Translation
For each Python construct below, write the equivalent JavaScript syntax without using an AI assistant. Then check your answers with AI.
# 1. Variable declaration
name = "Alice"
age = 30
is_active = True
# 2. List (array) operations
numbers = [1, 2, 3, 4, 5]
doubled = [n * 2 for n in numbers]
evens = [n for n in numbers if n % 2 == 0]
# 3. Dictionary (object)
user = {"name": "Alice", "age": 30, "email": "alice@example.com"}
# 4. Function definition
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# 5. Conditional expression
status = "active" if is_active else "inactive"
Exercise 3: Semantic HTML Element Selection
For each content type below, identify the most appropriate semantic HTML element. Choose from: <article>, <aside>, <nav>, <section>, <header>, <footer>, <main>, <figure>, <figcaption>, <details>, <time>, <address>.
- The primary content area of a page
- A blog post that could stand alone
- A sidebar with related links
- A date displayed on a page: "March 15, 2025"
- A list of navigation links
- An image with a descriptive caption
- A collapsible FAQ answer
- Contact information for the page author
Exercise 4: React Hook Identification
For each scenario, identify which React hook(s) you would use:
- Storing the current value of a search input field
- Fetching data from an API when a component first appears
- Sharing theme preferences across the entire application without prop drilling
- Storing a reference to a DOM element for direct manipulation
- Memoizing an expensive calculation that depends on a list of items
- Performing cleanup when a component is removed from the page
Exercise 5: CSS Layout Concepts
Answer the following questions about CSS layout:
- What is the difference between Flexbox and CSS Grid? When would you choose one over the other?
- What does "mobile-first" design mean in the context of media queries?
- What CSS unit would you use for font sizes that scale with the user's browser settings?
- What is the CSS box model, and how does
box-sizing: border-boxchange its behavior? - Explain the difference between
marginandpadding.
Exercise 6: Accessibility Checklist
Create a checklist of at least 10 accessibility requirements you should include when prompting AI to generate frontend code. Organize them into categories (visual, keyboard, screen reader, forms).
Tier 2: Apply (Exercises 7-12)
Exercise 7: Generate a Navigation Component
Write a prompt for your AI assistant to generate a responsive navigation bar with the following requirements: - Logo on the left - Navigation links in the center: Home, Products, About, Contact - A "Sign In" button on the right - On mobile, the links collapse into a hamburger menu - Active link should be highlighted - Use Tailwind CSS - Must be accessible (keyboard navigable, proper ARIA attributes)
Generate the component, then review the output for:
- Correct semantic HTML (<nav>, <ul>, <li>)
- Proper ARIA attributes for the mobile menu toggle
- Keyboard accessibility (can you Tab through all links?)
- Responsive behavior
Exercise 8: Build a Product Card Component
Using AI, create a React ProductCard component that displays:
- Product image with fallback for broken images
- Product name (truncated to 2 lines with ellipsis)
- Price with strikethrough original price if on sale
- Star rating (1-5 stars, showing half stars)
- "Add to Cart" button
- "Wishlist" heart icon toggle
Test the component with at least three different product data objects, including edge cases (very long name, no sale price, zero rating, missing image).
Exercise 9: Form with Validation
Create a user registration form using AI with the following fields and validation rules:
| Field | Type | Validation |
|---|---|---|
| Full Name | text | Required, 2-100 characters |
| Required, valid email format | ||
| Password | password | Required, 8+ chars, 1 uppercase, 1 lowercase, 1 number, 1 special char |
| Confirm Password | password | Must match password |
| Date of Birth | date | Required, must be 13+ years old |
| Terms Checkbox | checkbox | Must be checked |
Requirements: - Show validation errors below each field as the user types (after the field has been touched) - Show a password strength indicator - Disable the submit button until all fields are valid - Show a success message after submission
Exercise 10: API Data Display
Using AI, create a React component that:
1. Fetches a list of users from https://jsonplaceholder.typicode.com/users
2. Displays them in a responsive card grid
3. Each card shows: name, email, company name, and city
4. Includes a search bar that filters users by name (client-side)
5. Shows a loading skeleton while data is fetching
6. Shows an error message with a "Retry" button if the fetch fails
Exercise 11: Dark Mode Toggle
Implement a dark mode feature for a React application:
1. Create a ThemeContext that provides the current theme and a toggle function
2. Store the theme preference in localStorage so it persists across sessions
3. Respect the user's system preference (prefers-color-scheme) as the default
4. Create a toggle button component with sun/moon icons
5. Apply the theme using CSS custom properties (variables) on the :root element
6. Ensure smooth transition between themes with CSS transitions
Exercise 12: Responsive Layout Challenge
Create a dashboard layout using CSS Grid that: - Has a fixed sidebar (250px) on the left on desktop - Has a sticky header at the top - Has a main content area with a 3-column card grid - On tablet (< 1024px): sidebar collapses, content becomes 2-column - On mobile (< 640px): no sidebar (hamburger menu instead), single column - Cards should have a minimum width of 280px and grow to fill available space
Use grid-template-areas for the layout. Test at three breakpoints.
Tier 3: Analyze (Exercises 13-18)
Exercise 13: Code Review -- Spot the Problems
Review the following AI-generated React component and identify all issues (there are at least 8):
function UserList() {
const [users, setUsers] = useState();
const [search, setSearch] = useState("");
useEffect(() => {
fetch("/api/users")
.then(res => res.json())
.then(data => setUsers(data));
});
const filteredUsers = users.filter(u =>
u.name.toLowerCase().includes(search)
);
return (
<div>
<input
type="text"
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="Search users..."
/>
<ul>
{filteredUsers.map(user => (
<li>
<img src={user.avatar} />
<div class="user-name">{user.name}</div>
<div dangerouslySetInnerHTML={{
__html: user.bio
}} />
</li>
))}
</ul>
</div>
);
}
For each issue, explain: (a) what the problem is, (b) why it matters, and (c) how to fix it.
Exercise 14: State Management Analysis
You are building a social media dashboard with the following data: - Current user's profile and authentication status - A feed of posts (paginated, with real-time updates) - User's notification count (updates in real-time) - Draft post being composed - UI state: which modal is open, sidebar collapsed or expanded - Post filter settings (date range, category, author)
For each piece of data, analyze: 1. Where should this state live? (component-local, Context, URL params, or external store) 2. How frequently does it change? 3. How many components need access to it? 4. Are there any performance concerns?
Justify your decisions.
Exercise 15: Accessibility Audit
Use AI to generate a login page, then manually audit it for accessibility by checking:
- Can you complete the entire login flow using only the keyboard?
- Does every form input have a visible, associated label?
- Are error messages announced to screen readers (using
role="alert"oraria-live)? - Does the color contrast meet WCAG 2.1 AA standards (4.5:1 for normal text)?
- Is the focus indicator visible on all interactive elements?
- Does the password field have a show/hide toggle that is accessible?
- Is the form submission status announced to screen readers?
Document each finding and provide the fix.
Exercise 16: Performance Analysis
Given the following React component that displays a large list of 10,000 items, identify performance problems and propose solutions:
function LargeList({ items, onItemClick }) {
const [filter, setFilter] = useState("");
const filtered = items.filter(item =>
item.name.toLowerCase().includes(filter.toLowerCase())
);
const sorted = [...filtered].sort((a, b) =>
a.name.localeCompare(b.name)
);
return (
<div>
<input
value={filter}
onChange={e => setFilter(e.target.value)}
placeholder="Filter..."
/>
<div style={{ height: "500px", overflow: "auto" }}>
{sorted.map(item => (
<div
key={item.id}
onClick={() => onItemClick(item)}
style={{ padding: "10px", borderBottom: "1px solid #eee" }}
>
<h3>{item.name}</h3>
<p>{item.description}</p>
<span>{new Date(item.createdAt).toLocaleDateString()}</span>
</div>
))}
</div>
</div>
);
}
Consider: rendering performance, filtering/sorting efficiency, and user experience.
Exercise 17: Component Architecture Design
You are building an e-commerce product page that includes: - Product image gallery (main image + thumbnails) - Product info (title, price, description, rating) - Variant selector (size, color) - Quantity selector - Add to cart button (updates cart in header) - Product reviews section (paginated) - "Frequently bought together" recommendations
Design the component tree. For each component, specify: - Its name and responsibility - What props it receives - What state it manages internally - What callbacks it provides to parents
Draw the component hierarchy and data flow diagram.
Exercise 18: CSS Specificity Debugging
Explain why the following CSS produces unexpected results. The developer wants the .special-button to have a red background, but it remains blue:
<div id="app">
<section class="content">
<button class="btn primary special-button">Click Me</button>
</section>
</div>
.special-button {
background-color: red;
}
#app .content .btn.primary {
background-color: blue;
color: white;
padding: 10px 20px;
}
Explain the specificity calculation for each selector and provide three different ways to fix the issue without using !important.
Tier 4: Evaluate (Exercises 19-24)
Exercise 19: Framework Comparison
You need to build a small internal tool for your team (a project time tracker). Evaluate the following approaches:
- Vanilla HTML/CSS/JavaScript (no framework)
- React with Vite
- Vue.js with Vite
- A no-code tool like Retool or Appsmith
For each approach, evaluate: learning curve, development speed with AI, maintainability, performance, and deployment complexity. Write a recommendation with justification.
Exercise 20: Evaluate AI-Generated Code Quality
Ask three different AI prompts to generate the same component (a sortable data table). Compare the outputs on:
Prompt: "Create a React component for a sortable data table that displays user data (name, email, role, status) with column header click sorting."
Evaluate each output on: 1. Code organization and readability 2. Accessibility compliance 3. Edge case handling (empty data, single item, many items) 4. Performance considerations 5. Reusability (how easy to adapt for different data?)
Rate each on a 1-5 scale with justification.
Exercise 21: Styling Approach Evaluation
Create the same component (a pricing card) using three different styling approaches: 1. Plain CSS with BEM naming 2. Tailwind CSS utility classes 3. CSS-in-JS (styled-components or emotion)
For each, evaluate: - Developer experience (how pleasant is it to write and maintain?) - Bundle size impact - Runtime performance - AI generation quality (which produces the best results?) - Team scalability (how well does it work on a large team?)
Exercise 22: Security Review
Review the following React code for security vulnerabilities:
function SearchResults() {
const params = new URLSearchParams(window.location.search);
const query = params.get("q");
const [results, setResults] = useState([]);
useEffect(() => {
fetch(`/api/search?q=${query}`)
.then(res => res.json())
.then(data => setResults(data));
}, [query]);
return (
<div>
<h1>Results for: <span dangerouslySetInnerHTML={{
__html: query
}} /></h1>
{results.map(r => (
<div key={r.id}>
<a href={r.url}>{r.title}</a>
<div dangerouslySetInnerHTML={{ __html: r.snippet }} />
</div>
))}
</div>
);
}
Identify each vulnerability, explain the attack vector, and provide the secure alternative.
Exercise 23: Evaluate Responsive Design Strategies
You are building a data-heavy dashboard that shows charts, tables, and KPI cards. Evaluate three responsive strategies:
- Hide and show: Hide less important elements on small screens
- Reflow: Rearrange elements into a single column on small screens
- Dedicated mobile view: Build a completely different layout for mobile
For each strategy, consider: user experience, development effort, maintenance burden, and information density. Which would you recommend for a dashboard that executives use on their phones during meetings?
Exercise 24: Testing Strategy Evaluation
For a React e-commerce checkout flow (cart review, shipping form, payment form, confirmation), design a testing strategy. Evaluate:
- Which components need unit tests? Why?
- Which interactions need integration tests? Why?
- What would you test with end-to-end tests?
- Where would you use snapshot testing?
- What is not worth testing? Why?
Prioritize your tests by impact (what breaks would be most costly?).
Tier 5: Create (Exercises 25-30)
Exercise 25: Build a Weather Dashboard
Using AI as your co-pilot, build a complete weather dashboard that: - Accepts a city name input - Fetches weather data from a free API (e.g., Open-Meteo) - Displays current conditions (temperature, humidity, wind, condition icon) - Shows a 5-day forecast with daily high/low and condition icons - Includes a simple temperature chart for the next 24 hours - Is responsive (works on mobile and desktop) - Has a dark/light mode toggle - Handles loading, error, and empty states gracefully
Document your prompting process: what prompts did you use, what did you iterate on, and what did you fix manually?
Exercise 26: Create a Component Library
Build a small React component library with at least 6 components:
1. Button (variants: primary, secondary, outline, ghost; sizes: sm, md, lg)
2. Input (with label, helper text, error state, and icon support)
3. Card (with header, body, footer sections)
4. Badge (variants: info, success, warning, error)
5. Modal (with overlay, close button, title, accessible focus trap)
6. Tabs (accessible tab panel implementation)
Requirements: - Consistent design system (spacing, colors, typography) - All components are accessible - Each component has a usage example - Use CSS custom properties for theming
Exercise 27: Build a Markdown Editor
Create a split-pane Markdown editor with: - Left pane: textarea for writing Markdown - Right pane: real-time preview of rendered HTML - Toolbar with buttons for common formatting (bold, italic, headings, links, code blocks, lists) - Keyboard shortcuts for toolbar actions (Ctrl+B for bold, etc.) - Word and character count - Local storage auto-save (save draft every 30 seconds) - Export as HTML or download as .md file - Responsive: on mobile, toggle between edit and preview modes
Exercise 28: Interactive Data Visualization
Build a React dashboard page that visualizes data using only HTML/CSS (no chart libraries): - A horizontal bar chart showing sales by category - A simple line chart showing monthly trends (use SVG) - A donut/ring chart showing market share percentages - KPI cards with animated number counters - Data should be loaded from a JSON file or mock API - Charts should animate on initial render - Charts should be responsive - Include a tooltip that shows exact values on hover
Exercise 29: Full CRUD Application
Build a complete contact management application: - List view with search, sort, and filter capabilities - Add new contact form with validation - Edit existing contact (inline or modal) - Delete with confirmation dialog - Contact detail view with all information - Categories/tags for organizing contacts - Import/export contacts as CSV - Responsive design for mobile use - Uses a mock backend (JSON Server or local state)
Document every AI prompt you use and note where you had to iterate or fix issues.
Exercise 30: Portfolio Website
Build your personal portfolio website from scratch using AI: - Home page with hero section and brief introduction - Projects page showing your work with screenshots, descriptions, and links - Skills section with visual representation of proficiency - Contact form with validation - Blog section with at least one article (can be about your vibe coding experience) - Responsive across all device sizes - Accessible (passes WCAG 2.1 AA) - Performance optimized (Lighthouse score > 90) - Deploy to a free hosting platform (Vercel, Netlify, or GitHub Pages)
Share the deployed URL and your Lighthouse scores.