0% found this document useful (0 votes)
4 views62 pages

React & TailwindCSS

Tailwind CSS is a utility-first CSS framework that enables rapid design directly in HTML using reusable classes for spacing, color, layout, and typography. It supports mobile-first responsive design and offers extensive customization through a configuration file, making it faster and more consistent for developers. The document also covers advanced utilities, state variants, typography, and building reusable components with practical examples and assignments.

Uploaded by

Vishal Rokkam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views62 pages

React & TailwindCSS

Tailwind CSS is a utility-first CSS framework that enables rapid design directly in HTML using reusable classes for spacing, color, layout, and typography. It supports mobile-first responsive design and offers extensive customization through a configuration file, making it faster and more consistent for developers. The document also covers advanced utilities, state variants, typography, and building reusable components with practical examples and assignments.

Uploaded by

Vishal Rokkam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Tailwind CSS

Class 1: Introduction to Tailwind CSS

1. Introduction to Tailwind CSS

What is Tailwind CSS?

●​ Tailwind CSS is a utility-first CSS framework that allows you to design directly in
your HTML by applying utility classes.
●​ Instead of writing custom CSS rules, Tailwind provides a vast collection of small,
reusable classes that control things like spacing, color, layout, and typography.

Key Features:

●​ Utility-first approach: Build designs using predefined classes directly in your


HTML.
●​ Customization: Easily customize the look and feel by modifying the
configuration file.
●​ Mobile-first: Responsive design is built in, with utilities that work for all
breakpoints.

Benefits of using Tailwind CSS:

●​ Faster Development: Since you don't have to write CSS from scratch, you can
rapidly style your application.
●​ Consistency: Utility classes help ensure consistent styling throughout the
application.
●​ Customization: Tailwind’s configuration file allows deep customization for colors,
fonts, spacing, etc.
●​ Responsive design: Tailwind makes it easy to handle responsiveness through
its mobile-first utilities.
Example: Without Tailwind CSS vs. With Tailwind CSS

Without Tailwind CSS:

<div class="container">​
<h1 class="main-heading">Hello, World!</h1>​
</div>​

<style>​
.container {​
padding: 20px;​
background-color: #f0f0f0;​
}​

.main-heading {​
color: blue;​
font-size: 2rem;​
}​
</style>

With Tailwind CSS:


<div class="p-5 bg-gray-100">​
<h1 class="text-blue-500 text-2xl">Hello, World!</h1>​
</div>

2. Setting Up Tailwind CSS

Installing Tailwind CSS via npm:

You can install Tailwind CSS in your project using npm (Node Package Manager).

Steps:

1.​ Make sure you have Node.js installed on your system.


2.​ Initialize a new project by running: npm init -y
3.​Install Tailwind CSS: npm install tailwind css
4.​Create the configuration file: npx tailwindcss init
Setting up Tailwind CSS in a new project:

1.​ Create a src/style.css file and import Tailwind's base, components, and
utilities:

@tailwind base;​
@tailwind components;​
@tailwind utilities;

2.​ Configure Tailwind to remove unused CSS in production by adding paths to all of
your templates in the tailwind.config.js file:

module.exports = {​
content: ['./src/**/*.{html,js}'],​
theme: {​
extend: {},​
},​
plugins: [],​
}

Example: Using Tailwind CSS in a simple HTML file


<!DOCTYPE html>​
<html lang="en">​
<head>​
<meta charset="UTF-8">​
<meta name="viewport" content="width=device-width,
initial-scale=1.0">​
<title>Tailwind Setup</title>​
<link href="style.css" rel="stylesheet">​
</head>​
<body>​
<div class="p-8 bg-blue-200">​
<h1 class="text-3xl font-bold text-center text-blue-900">Tailwind
CSS is Ready!</h1>​
</div>​
</body>​
</html>
3. Utility-First Fundamentals

Basic Utility Classes:

Tailwind CSS provides utility classes that allow you to apply CSS properties directly to
your HTML elements.

●​ Spacing utilities: Control padding and margins with classes like p-4, m-8,
pt-2, etc.
●​ Typography utilities: Classes like text-xl, font-bold, leading-normal,
etc., help in controlling text appearance.
●​ Color utilities: Use classes like text-red-500, bg-blue-300,
border-gray-200 to apply colors.

Example:

<div class="bg-gray-100 p-6">​


<h1 class="text-3xl font-semibold text-blue-800 mb-4">Welcome to
Tailwind</h1>​
<p class="text-lg text-gray-600">Tailwind allows you to style your
HTML using utility classes.</p>​
</div>

●​ p-6: Applies padding of 1.5rem.


●​ text-3xl: Makes the text 3 times larger than the base size.
●​ text-blue-800: Makes the text dark blue.

4. Responsive Design

Introduction to Responsive Design in Tailwind:

Tailwind CSS supports mobile-first responsive design. By default, styles apply to


mobile, but you can adjust styles for different screen sizes using responsive classes.

Tailwind’s responsive classes use breakpoints:

●​ sm (640px)
●​ md (768px)
●​ lg (1024px)
●​ xl (1280px)
Using Responsive Utility Classes:

You can prefix classes with breakpoint names to apply them only at specific screen
sizes.

Example:

<div class="text-sm md:text-lg lg:text-xl">​


This text adjusts its size based on screen width.​
</div>

●​ On small screens, it uses text-sm.


●​ On medium screens (768px and up), it switches to text-lg.
●​ On large screens (1024px and up), it switches to text-xl.

Example with Flexbox and Responsive Classes:

<div class="flex flex-col md:flex-row space-y-4 md:space-y-0


md:space-x-4">​
<div class="p-4 bg-red-300">Column 1</div>​
<div class="p-4 bg-green-300">Column 2</div>​
<div class="p-4 bg-blue-300">Column 3</div>​
</div>

●​ The items stack vertically on small screens (flex-col).


●​ On medium screens (md), they display in a row (flex-row).
●​ The spacing between columns adjusts with md:space-x-4.

Breakpoints and Custom Configurations:

You can customize breakpoints in the tailwind.config.js file if you need different
breakpoints for your project.

Example:

module.exports = {​
theme: {​
extend: {​
screens: {​
'xs': '480px',​
},​
},​
},​
}

Assignment:

1.​ Introduction to Tailwind CSS


○​ Research and note down two more benefits of using Tailwind CSS in
projects.
○​ Compare Tailwind CSS with Bootstrap or another CSS framework you are
familiar with. What are the differences in terms of ease of use and design
flexibility?
2.​ Setting Up Tailwind CSS
○​ Set up Tailwind CSS in a new project from scratch.
○​ Create a simple page with Tailwind utilities to display a heading,
paragraph, and button with different background colors and padding.
3.​ Utility-First Fundamentals
○​ Using utility classes, create a card component with a title, image, and
description. Apply spacing and text utilities to make it look clean and
organized.
4.​ Responsive Design
○​ Build a responsive navigation bar with Tailwind. The navigation links
should stack vertically on small screens and horizontally on larger
screens. Add appropriate padding and background colors for a clean look.
Class 2: Advanced Tailwind CSS Utilities and State Variants

1. Deep Dive into Utilities

Flexbox and Grid Utilities

Flexbox: Tailwind provides utility classes for flexbox, making it easy to create layouts
with flexible boxes.

●​ Basic Flexbox Classes:


○​ flex: Makes an element a flex container.
○​ flex-row: Arranges children horizontally (default).
○​ flex-col: Arranges children vertically.
○​ justify-start, justify-center, justify-end: Aligns flex items
along the main axis.
○​ items-start, items-center, items-end: Aligns items along the
cross axis.

Example: Flexbox Layout

<div class="flex justify-between items-center p-4 bg-gray-100">​


<div class="p-2 bg-blue-300">Item 1</div>​
<div class="p-2 bg-green-300">Item 2</div>​
<div class="p-2 bg-red-300">Item 3</div>​
</div>

●​ justify-between: Distributes space evenly between items.


●​ items-center: Centers items along the cross-axis (vertically).

Grid: Tailwind also provides grid utilities to build layouts with grids.

●​ Basic Grid Classes:


○​ grid: Makes an element a grid container.
○​ grid-cols-2, grid-cols-3: Defines the number of columns.
○​ gap-4: Adds spacing between grid items.
Example: Grid Layout

<div class="grid grid-cols-2 gap-4 p-4 bg-gray-100">​


<div class="p-4 bg-blue-300">Item 1</div>​
<div class="p-4 bg-green-300">Item 2</div>​
<div class="p-4 bg-red-300">Item 3</div>​
<div class="p-4 bg-yellow-300">Item 4</div>​
</div>

grid-cols-2: Creates two equal columns.

gap-4: Adds spacing between grid items.

Sizing (Width, Height, Min/Max)

Tailwind allows you to control the sizing of elements with width, height, min-width, and
max-width utilities.

●​ Width Utilities:
○​ w-1/2: Sets the width to 50%.
○​ w-full: Sets the width to 100%.
○​ w-auto: Sets the width to auto.
●​ Height Utilities:
○​ h-32: Sets the height to a fixed value.
○​ h-screen: Sets the height to fill the screen.
●​ Min/Max Width and Height:
○​ min-w-full, min-h-screen: Sets minimum width/height.
○​ max-w-lg, max-h-32: Sets maximum width/height.

Example: Sizing Utilities

<div class="w-1/2 h-32 bg-blue-300">This box takes up half the width


and is 32px tall</div>​
<div class="w-full h-screen bg-green-300">This box fills the entire
screen</div>
Borders, Background, and Shadows

●​ Borders: Tailwind provides utilities for adding and customizing borders.


○​ border, border-2: Adds a border with default or specified thickness.
○​ border-gray-500: Sets border color.
○​ rounded-md, rounded-full: Controls border-radius for rounded
corners.
●​ Backgrounds:
○​ bg-blue-500: Sets the background color.
○​ bg-gradient-to-r from-blue-400 via-purple-500
to-pink-500: Creates a gradient background.
●​ Shadows:
○​ shadow: Adds a basic shadow.
○​ shadow-lg, shadow-xl: Adds larger shadows.

Example: Borders, Backgrounds, and Shadows

<div class="p-6 bg-blue-500 rounded-lg shadow-lg">​


<h2 class="text-white">A Box with Shadow and Rounded Corners</h2>​
</div>

2. State Variants

Tailwind allows you to apply styles based on the element's state, such as hover,
focus, and active.

Hover, Focus, and Active States

●​ Hover: Add styles when the element is hovered.


○​ hover:bg-blue-700: Changes the background color on hover.
●​ Focus: Add styles when the element is focused (useful for forms).
○​ focus:outline-none: Removes the default focus outline.
○​ focus:ring-2: Adds a focus ring around the element.
●​ Active: Add styles when the element is actively clicked.
○​ active:bg-blue-900: Changes the background when the element is
clicked.
Example: Hover, Focus, and Active States

<button class="bg-blue-500 hover:bg-blue-700 focus:ring-4


active:bg-blue-900 text-white font-bold py-2 px-4 rounded">​
Click Me​
</button>

●​ Hover: The button turns darker blue on hover.


●​ Focus: The button has a ring when focused.
●​ Active: The button turns even darker blue when clicked.

Pseudo-Classes and Customizing States

Tailwind supports various pseudo-classes that allow you to apply styles conditionally.

●​ Examples of Pseudo-Classes:
○​ first, last, nth-child: Apply styles to the first, last, or specific
children.
○​ focus-within: Applies styles when an element inside a container is
focused.

Example: First Child Pseudo-Class

<ul class="list-none">​
<li class="first:bg-blue-300 p-2">First Item</li>​
<li class="p-2">Second Item</li>​
<li class="p-2">Third Item</li>​
</ul>

●​ The first <li> gets a blue background because of the first:bg-blue-300


class.

Customizing States in Tailwind Config

You can add more custom states or variants in the tailwind.config.js file.

module.exports = {​
theme: {​
extend: {},​
},​
variants: {​
extend: {​
backgroundColor: ['active'],​
textColor: ['visited'],​
},​
},​
plugins: [],​
}

Assignment:

1.​ Flexbox and Grid Utilities:


○​ Create a responsive 3-column grid using Tailwind’s grid utilities. The grid
should display in one column on mobile and three columns on desktop.
○​ Create a header section with flexbox that aligns content horizontally with
space between items and centers them vertically.
2.​ Sizing (Width, Height, Min/Max):
○​ Create a card component that has a minimum width of 250px, a maximum
width of 600px, and occupies 50% of the parent container. Add some
content inside the card with fixed height and padding.
3.​ Borders, Backgrounds, and Shadows:
○​ Design a profile card with a circular profile image using border utilities, a
gradient background, and a shadow around the card.
4.​ Hover, Focus, and Active States:
○​ Create a form with input fields that change their border color on focus.
Also, add a button that changes its background color on hover and
becomes darker when clicked.
Class 3: Typography and Building Reusable Components with Tailwind
CSS

1. Typography

Typography is an essential aspect of web design as it controls how text is presented on


the page. Tailwind CSS offers a wide range of utilities to handle typography, including
font sizes, font weights, line heights, and text alignment.

Typographic Utilities

Tailwind provides simple utility classes to manage various aspects of typography:

●​ Font Size:
○​ text-xs, text-sm, text-base, text-lg, text-xl, etc.
●​ Font Weight:
○​ font-light, font-normal, font-medium, font-bold,
font-extrabold
●​ Line Height:
○​ leading-none, leading-tight, leading-snug, leading-relaxed
●​ Text Alignment:
○​ text-left, text-center, text-right, text-justify

Example: Typographic Utilities

<div class="p-4">​
<h1 class="text-4xl font-bold leading-tight text-center">Welcome to
Our Website</h1>​
<p class="text-base leading-relaxed text-left mt-4">​
Tailwind CSS provides a rich set of typography utilities that
make it easy to style your text. You can control font sizes, font
weights, line heights, and more.​
</p>​
</div>

●​ text-4xl: Makes the text large (36px).


●​ font-bold: Makes the text bold.
●​ leading-tight: Reduces line spacing.
●​ text-center: Centers the heading.

Customizing Font Sizes, Weights, and Line Heights

You can define custom font sizes, weights, and line heights in tailwind.config.js
if the built-in ones don't meet your needs.

module.exports = {​
theme: {​
extend: {​
fontSize: {​
'xxs': '0.5rem',​
'xxl': '2rem',​
},​
fontWeight: {​
extra: 950,​
},​
lineHeight: {​
'extra-loose': '2.5',​
},​
},​
},​
}

Handling Responsive Typography

Tailwind CSS makes it easy to apply different font sizes and styles based on screen
size.

●​ Responsive Text:
○​ Use responsive breakpoints to adjust typography for different devices.
○​ For example, text-lg sm:text-xl lg:text-3xl applies different
font sizes on mobile, small screens, and large screens.
Example: Responsive Typography

<div class="p-4">​
<h1 class="text-lg sm:text-xl md:text-2xl lg:text-4xl
font-bold">Responsive Heading</h1>​
<p class="text-base sm:text-lg leading-relaxed">​
This paragraph changes size depending on the screen width. On
mobile devices, it uses the base font size, but on larger screens, it
becomes larger.​
</p>​
</div>

●​ Mobile: text-lg
●​ Small screens: text-xl
●​ Medium screens: text-2xl
●​ Large screens: text-4xl

2. Building Reusable Components

Reusable components help create consistent design patterns across your application.
Tailwind’s utility-first approach allows you to easily build flexible, reusable components
such as buttons, forms, and navigation.

Creating Consistent Design Patterns with Components

Tailwind encourages creating small, reusable components that can be used throughout
your app. This not only speeds up development but also ensures a cohesive design
system.

Example: Reusable Button Component

<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold


py-2 px-4 rounded">​
Click Me​
</button>

●​ Classes used:
○​ bg-blue-500: Base background color.
○​ hover:bg-blue-700: Darker background on hover.
○​ text-white: White text.
○​ font-bold: Bold text.
○​ py-2 px-4: Padding.
○​ rounded: Rounded corners.

Example: Reusable Form Component

<form class="w-full max-w-lg">​


<div class="mb-4">​
<label class="block text-gray-700 text-sm font-bold mb-2"
for="username">​
Username​
</label>​
<input class="shadow appearance-none border rounded w-full py-2
px-3 text-gray-700 leading-tight focus:outline-none
focus:shadow-outline" id="username" type="text"
placeholder="Username">​
</div>​
<div class="mb-4">​
<label class="block text-gray-700 text-sm font-bold mb-2"
for="password">​
Password​
</label>​
<input class="shadow appearance-none border rounded w-full py-2
px-3 text-gray-700 leading-tight focus:outline-none
focus:shadow-outline" id="password" type="password"
placeholder="Password">​
</div>​
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold
py-2 px-4 rounded">​
Submit​
</button>​
</form>

Reusable Form Styles:

●​ Labels and inputs use consistent typography and spacing.


●​ Buttons follow the same reusable button design from above.
Using Utility Classes to Build Buttons, Forms, and Navigation

Utility classes make building custom and reusable buttons, forms, and navigation easy.

Example: Navigation Bar

<nav class="bg-gray-800 p-4">​


<ul class="flex space-x-4">​
<li><a href="#" class="text-white
hover:text-gray-300">Home</a></li>​
<li><a href="#" class="text-white
hover:text-gray-300">About</a></li>​
<li><a href="#" class="text-white
hover:text-gray-300">Contact</a></li>​
</ul>​
</nav>

●​ Classes used:
○​ bg-gray-800: Dark background for the navbar.
○​ text-white: White text.
○​ hover:text-gray-300: Changes text color on hover.
○​ flex space-x-4: Horizontal layout with space between links.

Example: Reusable Button with Variants

<button class="bg-green-500 hover:bg-green-700 text-white font-bold


py-2 px-4 rounded">Save</button>​
<button class="bg-red-500 hover:bg-red-700 text-white font-bold py-2
px-4 rounded">Delete</button>

Create different buttons (e.g., save, delete) with reusable utility classes by changing the
background colors (bg-green-500, bg-red-500).
Assignment:

1.​ Typography:
○​ Create a blog post layout using Tailwind’s typography utilities. The
heading should use different font sizes based on screen size. Include a
paragraph with adjusted line height and text alignment.
2.​ Reusable Components:
○​ Design a login form with reusable input fields and buttons. Ensure the
form has proper spacing and aligns well on different screen sizes. Each
form element should use consistent styling via utility classes.
○​ Create a navigation bar with three links. Ensure it’s responsive and
changes layout when viewed on mobile screens (e.g., turning into a
vertical list).
Class 4: Forms and Inputs in Tailwind CSS

1. Styling Forms with Tailwind CSS

Forms are critical components of many web applications, and Tailwind CSS provides a
rich set of utility classes to style form elements such as input fields, buttons, and labels
with ease.

Basic Form Styling

To create a basic form with Tailwind, you can utilize utility classes for spacing, borders,
padding, and text styles.

Example: Simple Form Layout

<form class="max-w-lg mx-auto mt-10 p-6 bg-white rounded-lg


shadow-md">​
<div class="mb-4">​
<label class="block text-gray-700 text-sm font-bold mb-2"
for="username">​
Username​
</label>​
<input class="shadow appearance-none border rounded w-full py-2
px-3 text-gray-700 leading-tight focus:outline-none
focus:shadow-outline" id="username" type="text" placeholder="Enter
your username">​
</div>​
<div class="mb-4">​
<label class="block text-gray-700 text-sm font-bold mb-2"
for="password">​
Password​
</label>​
<input class="shadow appearance-none border rounded w-full py-2
px-3 text-gray-700 leading-tight focus:outline-none
focus:shadow-outline" id="password" type="password"
placeholder="Enter your password">​
</div>​
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold
py-2 px-4 rounded">​
Submit​
</button>​
</form>

●​ Classes Used:
○​ max-w-lg mx-auto: Sets a maximum width for the form and centers it.
○​ bg-white rounded-lg shadow-md: Creates a white background with
rounded corners and a subtle shadow.
○​ mb-4: Adds space between form elements.
○​ text-gray-700 text-sm font-bold: Applies consistent typography
for labels.
○​ py-2 px-3: Adds padding inside the input fields.
○​ focus:outline-none focus:shadow-outline: Enhances focus
states for input fields.

Customizing Input Fields

You can modify input fields to have different styles by using utility classes for padding,
borders, colors, and more.

Example: Customized Input Fields

<input class="border border-gray-300 rounded-lg py-3 px-4 text-lg


text-gray-700 focus:border-blue-500 focus:outline-none focus:ring
focus:ring-blue-200" type="text" placeholder="Large Input Field">

border-gray-300: Applies a light gray border.

rounded-lg: Adds rounded corners.

py-3 px-4 text-lg: Sets larger padding and text size.

focus:border-blue-500: Changes the border color when the input is focused.

focus:ring: Adds a ring around the input during focus.


2. Customizing Input Fields, Checkboxes, and Radio Buttons

Tailwind allows easy customization of form controls like input fields, checkboxes, and
radio buttons by utilizing utilities for borders, shadows, and spacing.

Customizing Checkboxes and Radio Buttons

Checkboxes and radio buttons can be customized by applying utility classes for size,
color, and hover/focus states.

Example: Custom Checkbox

<label class="inline-flex items-center">​


<input type="checkbox" class="form-checkbox h-5 w-5 text-blue-600">​
<span class="ml-2 text-gray-700">Remember me</span>​
</label>

●​ form-checkbox: Applies default styles to checkboxes.


●​ h-5 w-5: Sets the height and width of the checkbox.
●​ text-blue-600: Changes the color of the checkbox when checked.

Example: Custom Radio Button

<label class="inline-flex items-center">​


<input type="radio" class="form-radio h-5 w-5 text-green-500"
name="radio-group">​
<span class="ml-2 text-gray-700">Option 1</span>​
</label>

form-radio: Applies default styles to radio buttons.

text-green-500: Changes the color of the radio button when selected.

3. Handling Form Validation States

Tailwind offers classes to indicate validation states for form inputs, such as when a user
inputs valid or invalid data.

Example: Input with Error State


<div class="mb-4">​
<label class="block text-red-700 text-sm font-bold mb-2"
for="email">​
Email​
</label>​
<input class="shadow appearance-none border border-red-500 rounded
w-full py-2 px-3 text-red-700 leading-tight focus:outline-none
focus:border-red-600" id="email" type="email" placeholder="Enter your
email">​
<p class="text-red-500 text-xs italic mt-2">Please enter a valid
email address.</p>​
</div>

●​ border-red-500 text-red-700: Indicates an error by using a red border


and red text.
●​ focus:border-red-600: Changes the border color on focus.
●​ text-xs italic: Styles the error message.

Example: Input with Success State

<div class="mb-4">​
<label class="block text-green-700 text-sm font-bold mb-2"
for="email">​
Email​
</label>​
<input class="shadow appearance-none border border-green-500
rounded w-full py-2 px-3 text-green-700 leading-tight
focus:outline-none focus:border-green-600" id="email" type="email"
placeholder="Email is valid">​
<p class="text-green-500 text-xs italic mt-2">Looks good!</p>​
</div>

border-green-500 text-green-700: Indicates a successful validation state with


green colors.

text-xs italic: Styles the success message.


Assignment:

1.​ Create a Custom Login Form:


○​ Build a login form using Tailwind CSS.
○​ Customize the input fields for username and password.
○​ Add proper validation messages and styles for success/error states (e.g.,
red borders for errors, green borders for success).
○​ Style the submit button to stand out with hover effects and focus states.
2.​ Build a Contact Form:
○​ Create a contact form with fields for name, email, and message.
○​ Customize the form using Tailwind’s utility classes, including text areas for
longer input (e.g., the message field).
○​ Include custom checkbox and radio button fields for user preferences
(e.g., select preferred contact method).
○​ Ensure the form is fully responsive.
Class 5: Animations and Transitions in Tailwind CSS

1. Adding Animations and Transitions with Utility Classes

Tailwind CSS simplifies the process of adding animations and transitions to your
elements by providing built-in utilities.

Transitions

With Tailwind, you can apply transitions to smoothly animate changes in styles like
color, background, or opacity when interacting with elements.

Example: Button Hover Transition

<button class="bg-blue-500 text-white font-bold py-2 px-4 rounded


transition duration-300 ease-in-out hover:bg-blue-700">​
Hover Me​
</button>

●​ transition: Enables transitions.


●​ duration-300: Sets the duration of the transition to 300ms.
●​ ease-in-out: Smoothens the transition with easing.
●​ hover:bg-blue-700: Changes the background color on hover.

Animations

Tailwind provides utility classes to create animations, such as spinning icons or


bouncing elements.

Example: Spinning Loader Animation

<div class="animate-spin h-10 w-10 border-4 border-blue-500


rounded-full"></div>

animate-spin: Makes the element spin.

h-10 w-10: Sets the size of the element.

border-4 border-blue-500: Styles the border for visibility.


2. Customizing Animations with Keyframes

Tailwind allows you to define custom animations using keyframes in the


tailwind.config.js file, enabling more flexibility for unique animations.

Example: Custom Bouncing Animation

1.​ Add Keyframes in Tailwind Config

// tailwind.config.js

module.exports = {​
theme: {​
extend: {​
keyframes: {​
bounce: {​
'0%, 100%': { transform: 'translateY(0)' },​
'50%': { transform: 'translateY(-25%)' },​
},​
},​
animation: {​
bounce: 'bounce 1s infinite',​
},​
},​
},​
}

2. Apply the Custom Animation

<div class="h-12 w-12 bg-green-500 animate-bounce"></div>

animate-bounce: Applies the custom bouncing animation.

3. Creating Smooth Transitions for Interactive Elements

Tailwind allows you to create smooth transitions for user interactions such as hover and
focus states by combining utilities for transitions, colors, opacity, and more.
Example: Smooth Background Transition for Card

<div class="max-w-sm rounded overflow-hidden shadow-lg transition


ease-in-out duration-300 hover:bg-gray-200">​
<img class="w-full" src="image.jpg" alt="Image">​
<div class="px-6 py-4">​
<div class="font-bold text-xl mb-2">Card Title</div>​
<p class="text-gray-700 text-base">This is a card with a smooth
hover effect.</p>​
</div>​
</div>

hover:bg-gray-200: Adds a background change on hover.

transition ease-in-out duration-300: Smoothens the background color


transition.

Assignment:

1.​ Create a Hover Effect for Buttons:


○​ Build a button with Tailwind that changes background color, border, and
scale on hover.
○​ Add smooth transitions between states (e.g., background color, size).
2.​ Animate an Icon:
○​ Use Tailwind’s animate-spin or a custom animation to spin an icon
when hovered.
○​ Customize the duration and easing of the animation.
Class 6: Handling Complex Layouts in Tailwind CSS

1. Creating Complex Grid Layouts

Tailwind provides a flexible grid system with utilities that allow you to create complex,
responsive layouts. You can define grid columns, rows, gaps, and more.

Example: Two-Column Layout

<div class="grid grid-cols-2 gap-4">​


<div class="bg-blue-500 p-4">Column 1</div>​
<div class="bg-green-500 p-4">Column 2</div>​
</div>

●​ grid grid-cols-2: Creates a grid with two columns.


●​ gap-4: Adds spacing between the grid items.

Example: Responsive Grid Layout

<div class="grid grid-cols-1 md:grid-cols-3 gap-6">​


<div class="bg-red-500 p-4">Column 1</div>​
<div class="bg-yellow-500 p-4">Column 2</div>​
<div class="bg-blue-500 p-4">Column 3</div>​
</div>

grid-cols-1 md:grid-cols-3: Creates a one-column grid for small screens, but


switches to a three-column grid for medium-sized screens (using the md breakpoint).

2. Building Responsive Navigation Bars

Tailwind CSS makes it easy to create fully responsive navigation bars using utility
classes for layout, spacing, and breakpoints.

Example: Responsive Navbar

<nav class="bg-gray-800 p-4">​


<div class="container mx-auto flex justify-between items-center">​
<a href="#" class="text-white text-xl">Logo</a>​
<ul class="hidden md:flex space-x-6">​
<li><a href="#" class="text-gray-300
hover:text-white">Home</a></li>​
<li><a href="#" class="text-gray-300
hover:text-white">About</a></li>​
<li><a href="#" class="text-gray-300
hover:text-white">Contact</a></li>​
</ul>​
<button class="block md:hidden text-gray-300">​
<svg class="h-6 w-6" fill="none" stroke="currentColor"
viewBox="0 0 24 24">​
<path stroke-linecap="round" stroke-linejoin="round"
stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>​
</svg>​
</button>​
</div>​
</nav>

md:flex: Shows the navigation items in a flex layout on medium-sized screens and
above.

hidden md:block: Hides the button on medium screens and above but shows it on
smaller screens.

3. Advanced Flexbox Techniques

Flexbox provides powerful utilities to create dynamic layouts with flexible alignment and
distribution of space.

Example: Centering Content Vertically and Horizontally

<div class="flex items-center justify-center h-screen">​


<div class="text-white text-2xl">Centered Content</div>​
</div>

flex items-center justify-center: Centers the content both vertically and


horizontally.

h-screen: Makes the container as tall as the viewport.


Assignment:

1.​ Build a Responsive Grid Layout:


○​ Create a responsive grid layout that displays two columns on small
screens and four columns on larger screens.
○​ Ensure that the layout adjusts dynamically using Tailwind’s responsive grid
utilities.
2.​ Design a Responsive Navbar:
○​ Build a fully responsive navigation bar with a hamburger menu for small
screens.
○​ The navbar should collapse into a button on mobile and expand into a full
menu on larger screens using flexbox and grid techniques.
React JS

Class 1: Introduction to ES6 Concepts in JavaScript

1. Arrow Functions

Arrow functions are a shorthand syntax for writing functions in ES6. They are especially
useful in React for handling events and creating functional components.

Syntax:

const add = (a, b) => a + b;

Example:
const greet = name => `Hello, ${name}`;​
console.log(greet(John)); // Output: "Hello, John"

Key Characteristics:

●​ Shorter syntax.
●​ Automatically bind this (no need for bind()).

2. Let and Const

●​ let: Used for block-scoped variables. The value can be reassigned.


●​ const: Used for constants that should not change.

Example:

let age = 25;​


const name = 'John';​
age = 26; // Allowed​
// name = 'Doe'; // Error
3. Template Literals

Template literals allow embedding expressions into strings, making string interpolation
easier.

Example:

const name = John;​


const greeting = `Hello, my name is ${name}`;​
console.log(greeting); // Output: "Hello, my name is John"

Benefits:

●​ Multi-line strings.
●​ String interpolation.

Assignment:

1.​ Create a simple function using an arrow function that takes two numbers as input
and returns their sum.
2.​ Rewrite a function using let and const, ensuring proper usage of
block-scoping.
Class 2: Advanced ES6 Concepts

4. Destructuring

Destructuring allows you to extract values from arrays or properties from objects into
distinct variables.

Example: Array Destructuring:

const [a, b] = [1, 2];​


console.log(a); // Output: 1

Example: Object Destructuring:


const person = { name: 'John', age: 30 };​
const { name, age } = person;​
console.log(name); // Output: "John"

5. Default Parameters

Default parameters allow you to initialize a function with default values.

Example:

const greet = (name = 'Guest') => `Hello, ${name}`;​


console.log(greet()); // Output: "Hello, Guest"

6. Spread and Rest Operators

●​ Spread (...): Expands an array or object into individual elements.


●​ Rest (...): Collects multiple elements into an array.

Example: Spread Operator:

const arr = [1, 2, 3];​


const newArr = [...arr, 4, 5];​
console.log(newArr); // Output: [1, 2, 3, 4, 5]
Example: Rest Operator:
const sum = (...numbers) => numbers.reduce((acc, num) => acc + num,
0);​
console.log(sum(1, 2, 3)); // Output: 6

Assignment:

1.​ Use destructuring to extract values from an object and an array.


2.​ Write a function with default parameters that returns a greeting message.
3.​ Create a function using the rest operator that takes any number of inputs and
returns their sum.
Class 3: Promises, Async/Await, and Array Methods

7. Object Literal Enhancements

Object literals allow you to create objects more concisely, especially when variable
names match property names.

Example:

const name = 'John';​


const age = 30;​
const person = { name, age };​
console.log(person); // Output: { name: 'John', age: 30 }

8. Modules

Modules allow you to export and import code between different JavaScript files,
promoting reusable and modular code.

Example:

// utils.js​
export const add = (a, b) => a + b;​

// main.js​
import { add } from './utils';​
console.log(add(2, 3)); // Output: 5

9. Promises and Async/Await

●​ Promises: Handle asynchronous operations. It can either resolve (success) or


reject (failure).

Example:

const myPromise = new Promise((resolve, reject) => {​


setTimeout(() => resolve('Promise resolved!'), 1000);​
});​
myPromise.then(result => console.log(result)); // Output: "Promise
resolved!"
●​ Async/Await: Simplifies working with promises by allowing you to write
asynchronous code as if it were synchronous.

Example:

const fetchData = async () => {​


const response = await
fetch('https://jsonplaceholder.typicode.com/posts');​
const data = await response.json();​
console.log(data);​
};​
fetchData();

10. Array Methods (map, filter, reduce)

●​ map(): Iterates over an array and returns a new array based on the callback
function.

Example:

const numbers = [1, 2, 3];​


const doubled = numbers.map(n => n * 2);​
console.log(doubled); // Output: [2, 4, 6]

●​ filter(): Returns a new array with elements that pass the test provided by a
function.

Example:

const numbers = [1, 2, 3, 4];​


const evenNumbers = numbers.filter(n => n % 2 === 0);​
console.log(evenNumbers); // Output: [2, 4]

●​ reduce(): Reduces the array to a single value by applying a function to each


element.
Example:

const numbers = [1, 2, 3, 4];​


const sum = numbers.reduce((acc, curr) => acc + curr, 0);​
console.log(sum); // Output: 10

Assignment:

1.​ Create an array of objects and use the map() method to display a specific
property from each object.
2.​ Fetch data using the Fetch API and display it in the console using
async/await.
3.​ Use filter() to extract elements that satisfy a condition and reduce() to
sum the elements of an array.
Class 4: Introduction to React Functional Components

1. What are Functional Components?

Functional components are JavaScript functions that return JSX, representing the UI in
a React application. They are stateless (don't manage their own state directly, though
they can use useState and other hooks).

Example:

function Greeting() {​
return <h1>Hello, World!</h1>;​
}

Functional components are simpler than class components and offer performance
improvements in modern React applications.

2. Benefits of Functional Components Over Class Components

●​ Simpler syntax: Functional components are just functions, making them easier to
read and write.
●​ Hooks support: With React Hooks, functional components can handle state
(useState), side effects (useEffect), and other advanced features without
needing class components.
●​ Performance: Functional components tend to be faster as they don’t involve the
overhead of creating class instances.
●​ Stateless or Stateful: While initially stateless, functional components can
manage state using React Hooks.

Class Component Example:

class Greeting extends React.Component {​


render() {​
return <h1>Hello, World!</h1>;​
}​
}

Functional Component Equivalent:


function Greeting() {​
return <h1>Hello, World!</h1>;​
}

3. Setting Up a React Development Environment

Before we dive into React development, you need to set up a React environment. This
can be done using Create React App, a tool that quickly scaffolds a React project with
all configurations in place.

Steps to Set Up React:

1.​ Install Node.js: Make sure you have Node.js installed. You can download it from
nodejs.org.
2.​ Install Create React App:

cd my-app

3.​ Navigate to Project Folder

npx create-react-app my-app

4.​ Run the Development Server:

npm start

This will launch a local development server at http://localhost:3000.​

4. JSX Syntax and Its Advantages

JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML
but allows embedding JavaScript expressions. JSX makes it easier to visualize the
structure of UI components.

Example:
function Welcome() {​
return <h1>Welcome to React!</h1>;​
}

●​ Advantages of JSX:
○​ Cleaner UI structure: Makes it easy to understand what the UI looks like.
○​ JavaScript Integration: Allows embedding JavaScript expressions within
the UI.
○​ Compiles to JavaScript: JSX is transformed into regular JavaScript
under the hood, making it compatible with browsers.

5. Creating and Rendering Functional Components

Functional components are created by defining a function that returns JSX. They can be
rendered into the DOM using ReactDOM.render() in the root component (typically
index.js).

Example: Creating and Rendering a Functional Component:

import React from 'react';​


import ReactDOM from 'react-dom';​

function Greeting() {​
return <h1>Hello, React!</h1>;​
}​

ReactDOM.render(<Greeting />, document.getElementById('root'));

This example defines a Greeting component and renders it to the root element in
index.html.

6. Embedding Expressions in JSX

JSX allows embedding JavaScript expressions inside curly braces {}. You can include
variables, function calls, and expressions directly inside your JSX.

Example:
function UserInfo() {​
const name = 'Shoubhik';​
const age = 25;​
return (​
<div>​
<h1>Name: {name}</h1>​
<p>Age: {age}</p>​
</div>​
);​
}​

ReactDOM.render(<UserInfo />, document.getElementById('root'));

Embedding Expressions: You can embed any valid JavaScript expression, like calling
functions or performing calculations:

<p>The sum is: {5 + 10}</p>

Assignment:

1.​ Set up a new React project using Create React App.


2.​ Create two functional components:
○​ One that displays a simple greeting message.
○​ Another that takes a name as a variable and displays a personalized
greeting.
3.​ Embed JavaScript expressions in the JSX of the second component to show
dynamic values.
Class 5: Conditional Rendering and Lists

In React, rendering components or elements conditionally and working with lists are
core concepts. This class will cover:

1.​ Conditional Rendering


○​ Using ternary operators and short-circuiting.
2.​ Rendering Lists
○​ Using the map() function.
○​ Importance of key prop for list items.

1. Conditional Rendering

Conditional rendering in React allows you to display different components or elements


based on certain conditions. This technique makes your app dynamic, responding to
different data or user actions.

a) Using Ternary Operators

Ternary operators offer a shorthand way to perform conditional rendering.

Syntax:

condition ? <ComponentIfTrue /> : <ComponentIfFalse />

Example:
function UserGreeting({ isLoggedIn }) {​
return (​
<div>​
{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}​
</div>​
);​
}

●​ Here, if isLoggedIn is true, "Welcome back!" displays; otherwise, "Please log


in." does.

b) Using Short-Circuiting
Short-circuiting is a way to conditionally render something only if a condition is true,
without needing an else part.

Syntax:

condition && <ComponentIfTrue />

Example:
function Notifications({ hasNotifications }) {​
return (​
<div>​
{hasNotifications && <p>You have new notifications!</p>}​
</div>​
);​
}

Here, p only renders if hasNotifications is true.

2. Rendering Lists

Rendering lists is another essential part of building applications, particularly when you
have an array of items you want to display, such as a list of users or products.

a) Using map() Function

In React, we use the map() function to iterate over arrays and render a component or
element for each item in the list.

Example:

function TodoList({ todos }) {​


return (​
<ul>​
{todos.map((todo, index) => (​
<li key={index}>{todo}</li>​
))}​
</ul>​
);​
}
●​ Here, each todo item is displayed as a li element.

b) Importance of key Prop

The key prop helps React identify which items have changed, are added, or removed. It
helps improve the rendering performance by allowing React to re-render only the items
that change.

In the previous example:

<li key={index}>{todo}</li>

The key prop is set to index. Typically, unique IDs are preferred over indexes to avoid
issues when the list order changes.

Assignment

1.​ Create a ProductList component that:


○​ Takes a list of products with names and prices.
○​ Uses map() to render each product's name and price.
○​ Applies conditional rendering: if the price is above 100, show "Expensive"
next to it; otherwise, show "Affordable."
2.​ Create a UserStatus component that:
○​ Displays "Welcome back!" if a user is logged in, and "Please log in." if not,
using a ternary operator.
○​ Add a second conditional statement to show "You have new messages!"
only if the user has messages (use short-circuiting).

Note: This will reinforce the use of ternary operators, short-circuiting, the map()
function, and proper use of the key prop.
Class 6: Props and Prop Types

In React, props are a way to pass data from parent to child components, enabling
component reuse and dynamic content. Using Prop Types helps ensure that the data
passed to components is valid, aiding in debugging and maintaining the codebase.

This class covers:

1.​ Passing Data to Functional Components Using Props


2.​ Defining Prop Types for Type Checking

1. Passing Data to Functional Components Using Props

Props (short for “properties”) allow data to be passed from a parent component to a
child component. They are read-only, meaning that a child component cannot modify
the props it receives.

How to Pass and Access Props

Props are passed to components as attributes within JSX and can be accessed in the
component by referring to the props parameter.

Example:

// Parent Component​
function App() {​
return <Greeting name="John" />;​
}​

// Child Component​
function Greeting(props) {​
return <p>Hello, {props.name}!</p>;​
}

●​ Here, App passes a name prop to Greeting, which is accessed in Greeting


as props.name.

Using Destructuring to Access Props


For convenience, props can be destructured directly in the component’s parameter.

Example:

function Greeting({ name }) {​


return <p>Hello, {name}!</p>;​
}

●​ This makes the code cleaner, especially when passing multiple props.

2. Defining Prop Types for Type Checking

Prop Types are used to define the types and constraints of props passed to a
component, ensuring the data is of the expected type and structure.

How to Use Prop Types

React has a library, prop-types, which helps in defining Prop Types. You’ll need to
install it first:

npm install prop-types

Once installed, you can specify the Prop Types for a component to make sure that the
props passed in match the expected data type.

Example:

import PropTypes from 'prop-types';​



function Greeting({ name, age }) {​
return (​
<p>​
Hello, {name}! You are {age} years old.​
</p>​
);​
}​

Greeting.propTypes = {​
name: PropTypes.string.isRequired, // Ensures `name` is a required
string​
age: PropTypes.number, // Ensures `age` is a number if
provided​
};

●​ Here, name must be a string and is required, while age is optional but must be a
number if provided.

Common Prop Types

Here are a few common types:

●​ PropTypes.string for strings.


●​ PropTypes.number for numbers.
●​ PropTypes.bool for booleans.
●​ PropTypes.array for arrays.
●​ PropTypes.object for objects.
●​ PropTypes.func for functions.
●​ PropTypes.element for React elements.
Assignment

1.​ Create a ProfileCard component that:


○​ Takes name, age, and isMember props.
○​ Displays the name and age, and conditionally shows “Member” if
isMember is true.
○​ Use Prop Types to ensure:
■​ name is a required string.
■​ age is an optional number.
■​ isMember is an optional boolean.
2.​ Create a Product component that:
○​ Accepts productName and price as props.
○​ Uses Prop Types to ensure productName is a required string and price
is a required number.
○​ Display a message: if price is above 50, show “Premium Product”;
otherwise, show “Standard Product.”

Note: This assignment will reinforce the use of props, prop destructuring, and Prop
Types for type checking.
Classes 7, 8, & 9: State Management with React Hooks

React Hooks provide a powerful way to manage component state and lifecycle features
in functional components. These classes will cover foundational hooks like useState
and useEffect before moving on to advanced hooks and custom hooks for more
efficient and reusable state management.

Class Breakdown:

●​ Class 7: useState and useEffect basics, side effects with useEffect


●​ Class 8: Advanced Hooks - useContext, useReducer
●​ Class 9: Advanced Hooks - useCallback, useMemo, useRef, and creating
Custom Hooks

Class 7: Basic State Management with useState and useEffect

1. useState

The useState hook allows you to add local state to functional components. It returns
an array containing the current state and a function to update that state.

Syntax:

const [state, setState] = useState(initialValue);

Example: Counter Component

import React, { useState } from 'react';​



function Counter() {​
const [count, setCount] = useState(0);​

return (​
<div>​
<p>Current count: {count}</p>​
<button onClick={() => setCount(count + 1)}>Increment</button>​
</div>​
);}
2. useEffect

The useEffect hook is used to perform side effects in a function component. Side
effects can include data fetching, subscriptions, and manually updating the DOM.

Syntax:

useEffect(() => {​
// Side effect code here​
}, [dependencies]);

Example: Fetching Data


import React, { useState, useEffect } from 'react';​

function DataFetcher() {​
const [data, setData] = useState(null);​

useEffect(() => {​
fetch('https://api.example.com/data')​
.then((response) => response.json())​
.then((data) => setData(data));​
}, []); // Empty dependency array, runs only once on mount​

return (​
<div>​
{data ? <p>Data: {data}</p> : <p>Loading...</p>}​
</div>​
);​
}

Assignment for Class 7:

1.​ Create a ToggleComponent using useState that toggles between "ON" and
"OFF" text when a button is clicked.
2.​ Create a TimerComponent that starts a countdown from 10 when the
component mounts, using useEffect.
Class 8: Advanced Hooks - useContext and useReducer

1. useContext

The useContext hook allows you to access context values directly without needing to
use the Consumer component, making it simpler to pass data through a component
tree.

Example: Theme Context

import React, { useContext } from 'react';​



const ThemeContext = React.createContext('light');​

function ThemeDisplay() {​
const theme = useContext(ThemeContext);​
return <div>Current Theme: {theme}</div>;​
}​

function App() {​
return (​
<ThemeContext.Provider value="dark">​
<ThemeDisplay />​
</ThemeContext.Provider>​
);​
}

2. useReducer

The useReducer hook is ideal for handling more complex state logic, like when you
have multiple states that depend on each other.

Syntax:

const [state, dispatch] = useReducer(reducerFunction, initialState);

Example: Counter with Reducer


import React, { useReducer } from 'react';​

const initialState = { count: 0 };​

function reducer(state, action) {​
switch (action.type) {​
case 'increment':​
return { count: state.count + 1 };​
case 'decrement':​
return { count: state.count - 1 };​
default:​
throw new Error();​
}​
}​

function Counter() {​
const [state, dispatch] = useReducer(reducer, initialState);​

return (​
<div>​
<p>Count: {state.count}</p>​
<button onClick={() => dispatch({ type: 'increment'
})}>+</button>​
<button onClick={() => dispatch({ type: 'decrement'
})}>-</button>​
</div>​
);​
}

Assignment for Class 8:

1.​ Create a LanguageContext and use useContext in two components to


display a message in the selected language.
2.​ Create a CounterReducer component using useReducer to manage
increment and decrement actions.
Class 9: Advanced Hooks - useCallback, useMemo, useRef, and Custom
Hooks

1. useCallback

The useCallback hook memoizes functions, which is useful when you want to prevent
re-creating a function on every render.

Example: Memoized Callback

import React, { useState, useCallback } from 'react';​



function Counter() {​
const [count, setCount] = useState(0);​

const increment = useCallback(() => {​
setCount((c) => c + 1);​
}, []);​

return (​
<div>​
<p>Count: {count}</p>​
<button onClick={increment}>Increment</button>​
</div>​
);​
}

2. useMemo

The useMemo hook memoizes values, so a calculation only re-runs if its dependencies
change. Useful for expensive calculations.

Example: Memoized Calculation

import React, { useState, useMemo } from 'react';​



function ExpensiveCalculation({ num }) {​
const result = useMemo(() => {​
let total = 0;​
for (let i = 0; i < 100000; i++) {​
total += i;​
}​
return total + num;​
}, [num]);​

return <p>Result: {result}</p>;​
}

3. useRef

The useRef hook can persist a mutable value across renders or reference DOM
elements.

Example: Ref in Input Field

import React, { useRef } from 'react';​



function FocusInput() {​
const inputRef = useRef(null);​

const focusInput = () => {​
inputRef.current.focus();​
};​

return (​
<div>​
<input ref={inputRef} type="text" />​
<button onClick={focusInput}>Focus Input</button>​
</div>​
);​
}

4. Custom Hooks

Custom hooks allow you to extract and reuse component logic across multiple
components.
Example: useFetch Custom Hook

import { useState, useEffect } from 'react';​



function useFetch(url) {​
const [data, setData] = useState(null);​

useEffect(() => {​
fetch(url)​
.then((res) => res.json())​
.then((data) => setData(data));​
}, [url]);​

return data;​
}​

// Usage in Component​
function DisplayData() {​
const data = useFetch('https://api.example.com/data');​

return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;​
}

Assignment for Class 9:

1.​ Create a useLocalStorage custom hook to manage saving and retrieving data
from local storage.
2.​ Create a useToggle custom hook that toggles a boolean value, and use it in a
component to show or hide text.
Class 10: Handling Events in Functional Components

Handling events in React is essential for creating interactive applications. In functional


components, we often use event handlers to update component state based on user
actions. This class will cover:

1.​ State Updates with Event Handlers


2.​ Using the Spread Operator for State Updates

1. State Updates with Event Handlers

In React, we can handle user interactions like clicks, typing, and form submissions
using event handlers. Event handlers are typically attached to elements, such as
buttons or input fields, and update the component state based on user actions.

Example: Handling Button Clicks to Update State

import React, { useState } from 'react';​



function Counter() {​
const [count, setCount] = useState(0);​

const handleIncrement = () => {​
setCount(count + 1);​
};​

return (​
<div>​
<p>Count: {count}</p>​
<button onClick={handleIncrement}>Increment</button>​
</div>​
);​
}

●​ Here, handleIncrement updates count each time the button is clicked.


Example: Handling Input Changes

import React, { useState } from 'react';​



function NameForm() {​
const [name, setName] = useState('');​

const handleChange = (event) => {​
setName(event.target.value);​
};​

return (​
<div>​
<input type="text" value={name} onChange={handleChange} />​
<p>Your name is: {name}</p>​
</div>​
);​
}
Class 11: Styling Functional Components

Styling components is a key part of building visually appealing and user-friendly


applications. In React, there are various ways to style functional components, each with
its own use cases and benefits. This class will cover:

1.​ Inline Styles with JSX


2.​ CSS Modules for Local Styles
3.​ CSS-in-JS Libraries (e.g., Tailwind CSS)

1. Inline Styles with JSX

Inline styles in React are written as objects, where the CSS property names are
camel-cased. This approach is quick for adding unique styles directly to an element but
is best used for small, component-specific styles.

Example: Button with Inline Styles

import React from 'react';​



function StyledButton() {​
return (​
<button​
style={{​
backgroundColor: 'blue',​
color: 'white',​
padding: '10px 20px',​
borderRadius: '5px',​
}}​
>​
Click Me​
</button>​
);​
}​

export default StyledButton;
●​ Inline styles are defined as an object, and each style property is camel-cased
(e.g., backgroundColor instead of background-color).
●​ This approach is useful for quick, unique styles but can become hard to manage
for complex styles.

2. CSS Modules for Local Styles

CSS Modules allow us to create locally scoped CSS, which means that styles defined in
a CSS Module only apply to the component in which they're imported. This prevents
class name collisions and makes it easier to manage component-specific styles.

Setup: In React, create a CSS file with the .module.css extension (e.g.,
Button.module.css).

Example: Button with CSS Modules

●​ Button.module.css

.button {​
background-color: green;​
color: white;​
padding: 10px 20px;​
border-radius: 5px;​
cursor: pointer;​
}

Button.js

import React from 'react';​


import styles from './Button.module.css';​

function Button() {​
return <button className={styles.button}>Click Me</button>;​
}​

export default Button;
●​ In this example, Button imports Button.module.css and applies the locally
scoped class using styles.button.
●​ This approach is useful when you want modular and reusable styles that are
specific to each component.

3. CSS-in-JS Libraries (e.g., Tailwind CSS)

CSS-in-JS libraries like Tailwind CSS provide utility-first styling with pre-defined classes,
making it easy to style components without writing separate CSS files. Tailwind CSS
allows you to apply styles directly in JSX, using utility classes to quickly build responsive
layouts.

Using Tailwind CSS with React

To use Tailwind CSS, install it and configure it in your project. Once set up, Tailwind
classes can be used directly within JSX.

Example: Button Styled with Tailwind CSS

import React from 'react';​



function TailwindButton() {​
return (​
<button className="bg-blue-500 text-white py-2 px-4 rounded">​
Click Me​
</button>​
);​
}​

export default TailwindButton;

●​ Here, classes like bg-blue-500, text-white, py-2, px-4, and rounded are
utility classes provided by Tailwind CSS to handle common styling needs directly
in the component.
●​ Tailwind CSS is popular for its simplicity, quick styling, and responsive design
features.
Assignment

1.​ Create a ProfileCard component styled with each of the following


approaches:
○​ Inline styles for the card’s container.
○​ CSS Module to style the text inside the card.
○​ Tailwind CSS for button styling in the card.
2.​ Build a ProductCard component that:
○​ Displays a product name, description, and price.
○​ Uses CSS Modules to define the styles for text.
○​ Styles the “Add to Cart” button with Tailwind CSS classes.

This assignment will give practice with different styling methods, and demonstrate when
and how to use each approach. Let me know if you'd like more examples or further
details on Tailwind setup!
Class 12: Fetching Data from APIs

Fetching data from APIs is a common task in web applications, especially for loading
dynamic content. This class will cover:

1.​ Using the useEffect Hook to Fetch Data


2.​ Using the Axios Library for HTTP Requests
3.​ Displaying Fetched Data in Functional Components

1. Using the useEffect Hook to Fetch Data

The useEffect hook is typically used to manage side effects, like fetching data from
an API when a component mounts. When we place a data-fetching function inside
useEffect with an empty dependency array, it only runs once when the component
loads.

Example: Fetch Data on Component Mount

import React, { useState, useEffect } from 'react';​



function DataFetcher() {​
const [data, setData] = useState(null);​

useEffect(() => {​
fetch('https://jsonplaceholder.typicode.com/posts/1')​
.then((response) => response.json())​
.then((json) => setData(json));​
}, []); //Empty dependency array ensures it runs only once on mount​

return (​
<div>​
{data ? <p>Title: {data.title}</p> : <p>Loading...</p>}​
</div>​
);​
}​

export default DataFetcher;
Explanation: In this example, fetch is used to get data from an API. The useEffect
hook runs on component mount to initiate the API call, and then updates the data state
once the response is received.

2. Using the Axios Library for HTTP Requests

Axios is a popular library for making HTTP requests in JavaScript. It provides a more
concise syntax than fetch and supports features like automatic JSON conversion,
request timeouts, and request interceptors.

Setting Up Axios: Install Axios via npm:

npm install axios

Example: Fetch Data with Axios


import React, { useState, useEffect } from 'react';​
import axios from 'axios';​

function AxiosDataFetcher() {​
const [data, setData] = useState(null);​

useEffect(() => {​
axios.get('https://jsonplaceholder.typicode.com/posts/1')​
.then((response) => setData(response.data))​
.catch((error) => console.error('Error fetching data:',
error));​
}, []);​

return (​
<div>​
{data ? <p>Title: {data.title}</p> : <p>Loading...</p>}​
</div>​
);​
}​

export default AxiosDataFetcher;

You might also like