React & TailwindCSS
React & TailwindCSS
● 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:
● 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
<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>
You can install Tailwind CSS in your project using npm (Node Package Manager).
Steps:
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: [],
}
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:
4. Responsive Design
● 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:
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:
Flexbox: Tailwind provides utility classes for flexbox, making it easy to create layouts
with flexible boxes.
Grid: Tailwind also provides grid utilities to build layouts with grids.
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.
2. State Variants
Tailwind allows you to apply styles based on the element's state, such as hover,
focus, and active.
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.
<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>
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. Typography
Typographic Utilities
● 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
<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>
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',
},
},
},
}
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
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.
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.
● 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.
Utility classes make building custom and reusable buttons, forms, and navigation easy.
● 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.
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
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.
To create a basic form with Tailwind, you can utilize utility classes for spacing, borders,
padding, and text styles.
● 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.
You can modify input fields to have different styles by using utility classes for padding,
borders, colors, and more.
Tailwind allows easy customization of form controls like input fields, checkboxes, and
radio buttons by utilizing utilities for borders, shadows, and spacing.
Checkboxes and radio buttons can be customized by applying utility classes for size,
color, and hover/focus states.
Tailwind offers classes to indicate validation states for form inputs, such as when a user
inputs valid or invalid data.
<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>
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.
Animations
// tailwind.config.js
module.exports = {
theme: {
extend: {
keyframes: {
bounce: {
'0%, 100%': { transform: 'translateY(0)' },
'50%': { transform: 'translateY(-25%)' },
},
},
animation: {
bounce: 'bounce 1s infinite',
},
},
},
}
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
Assignment:
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.
Tailwind CSS makes it easy to create fully responsive navigation bars using utility
classes for layout, spacing, and breakpoints.
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.
Flexbox provides powerful utilities to create dynamic layouts with flexible alignment and
distribution of space.
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:
Example:
const greet = name => `Hello, ${name}`;
console.log(greet(John)); // Output: "Hello, John"
Key Characteristics:
● Shorter syntax.
● Automatically bind this (no need for bind()).
Example:
Template literals allow embedding expressions into strings, making string interpolation
easier.
Example:
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.
5. Default Parameters
Example:
Assignment:
Object literals allow you to create objects more concisely, especially when variable
names match property names.
Example:
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
Example:
Example:
● map(): Iterates over an array and returns a new array based on the callback
function.
Example:
● filter(): Returns a new array with elements that pass the test provided by a
function.
Example:
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
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.
● 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.
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.
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
npm start
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.
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).
This example defines a Greeting component and renders it to the root element in
index.html.
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:
Assignment:
In React, rendering components or elements conditionally and working with lists are
core concepts. This class will cover:
1. Conditional Rendering
Syntax:
Example:
function UserGreeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
</div>
);
}
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:
Example:
function Notifications({ hasNotifications }) {
return (
<div>
{hasNotifications && <p>You have new notifications!</p>}
</div>
);
}
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.
In React, we use the map() function to iterate over arrays and render a component or
element for each item in the list.
Example:
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.
<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
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.
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.
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>;
}
Example:
● This makes the code cleaner, especially when passing multiple props.
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.
React has a library, prop-types, which helps in defining Prop Types. You’ll need to
install it first:
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:
● Here, name must be a string and is required, while age is optional but must be a
number if provided.
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:
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:
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]);
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.
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:
1. useCallback
The useCallback hook memoizes functions, which is useful when you want to prevent
re-creating a function on every render.
2. useMemo
The useMemo hook memoizes values, so a calculation only re-runs if its dependencies
change. Useful for expensive calculations.
3. useRef
The useRef hook can persist a mutable value across renders or reference DOM
elements.
4. Custom Hooks
Custom hooks allow you to extract and reuse component logic across multiple
components.
Example: useFetch Custom Hook
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
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.
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.
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).
● Button.module.css
.button {
background-color: green;
color: white;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
Button.js
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.
To use Tailwind CSS, install it and configure it in your project. Once set up, Tailwind
classes can be used directly within JSX.
● 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
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:
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.
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.