diff --git a/absolute-beginners/full-stack/backend/_category_.json b/absolute-beginners/full-stack/backend/_category_.json new file mode 100644 index 0000000..3da7068 --- /dev/null +++ b/absolute-beginners/full-stack/backend/_category_.json @@ -0,0 +1,9 @@ +{ + "label": "Backend Development", + "position": 8, + "link": { + "type": "generated-index", + "title": "Backend Development: The Brain of the App", + "description": "Step behind the curtain and learn how to build powerful servers, manage databases, and create secure APIs. This track covers everything from Node.js and Express to database architecture and authentication." + } +} \ No newline at end of file diff --git a/absolute-beginners/full-stack/backend/introduction.mdx b/absolute-beginners/full-stack/backend/introduction.mdx index e345ed2..2d3bb4c 100644 --- a/absolute-beginners/full-stack/backend/introduction.mdx +++ b/absolute-beginners/full-stack/backend/introduction.mdx @@ -1 +1,63 @@ - \ No newline at end of file +--- +title: "Introduction to Backend Development" +sidebar_label: "1. Introduction" +sidebar_position: 1 +description: "Understand what happens behind the scenes of a website and learn about the Client-Server architecture. Get an overview of the backend tech stack and how it connects to the frontend." +--- + +Welcome to the "Brain" of the application! If you've been following the **CodeHarborHub** track, you already know how to build beautiful interfaces with React and Tailwind. Now, it's time to learn how to make those interfaces **functional** and **persistent**. + +## 1. What exactly is the "Backend"? + +The Backend (also called "Server-Side") is the part of the website you cannot see. It is responsible for: +* **Storing Data:** Saving user profiles, blog posts, and passwords in a database. +* **Business Logic:** Calculating the total of a shopping cart or checking if a user has permission to delete a post. +* **Communication:** Sending emails, processing payments, and talking to other services. + +## 2. The Client-Server Architecture + +To understand the backend, you must understand the relationship between the **Client** and the **Server**. + +1. **The Client (Frontend):** This is the user's browser (Chrome, Safari) or a mobile app. It sends a **Request** (e.g., "Hey, I want to see Ajay's profile!"). +2. **The Server (Backend):** This is a computer located somewhere in the world that stays on 24/7. It receives the request, talks to the **Database**, and sends back a **Response** (e.g., "Here is the data for Ajay's profile."). + +## 3. The Backend "Tech Stack" + +A professional backend at the Hub usually consists of three main parts: + +### 1. The Server (The Application) +This is the code that handles requests. We will use **Node.js** with **Express.js**. Node.js allows us to use JavaScript (the same language you used for React!) to write server-side code. + +### 2. The Database (The Memory) +Servers don't "remember" things once they restart. For permanent storage, we use databases. +* **Relational (SQL):** Like a spreadsheet (e.g., PostgreSQL). +* **Non-Relational (NoSQL):** Like a collection of JSON documents (e.g., **MongoDB**). + +### 3. The API (The Bridge) +The **API** (Application Programming Interface) is the set of "doors" the server opens for the client. When you fetch a weather report or a cricket score, you are talking to an API. + +## 4. A Real-World Example: Logging In + +Let's see how the frontend and backend work together when you log into **CodeHarborHub**: + +1. **Frontend:** You type your email and password and click "Login." +2. **Request:** The frontend sends that data to the server via an API. +3. **Backend Logic:** The server receives the data. It doesn't know who you are yet. +4. **Database Check:** The server asks the database: *"Do we have a user with this email?"* and *"Does this password match the one we have saved?"* +5. **Response:** + * **If Yes:** The server sends back a "Success" message and a digital "key" (token). + * **If No:** The server sends back an "Error" message. +6. **Frontend:** The frontend sees the response and either takes you to your dashboard or shows an error. + +## The Roadmap Ahead + +In this module, we will follow this path to becoming a Backend pro: +* **Node.js Basics:** Learning to run JavaScript on your computer. +* **Express.js:** Creating your first web server. +* **Routing:** Handling different URL paths (like `/api/users` vs `/api/products`). +* **Databases:** Connecting to MongoDB to save real data. +* **Authentication:** Making sure users can log in securely. + +:::info for Noobs +Don't be intimidated! Since you already know JavaScript from the Frontend track, you are already 50% of the way there. The logic is the same—only the environment has changed. +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/_category_.json b/absolute-beginners/full-stack/frontend/_category_.json new file mode 100644 index 0000000..3a7e9e3 --- /dev/null +++ b/absolute-beginners/full-stack/frontend/_category_.json @@ -0,0 +1,9 @@ +{ + "label": "Frontend Development", + "position": 7, + "link": { + "type": "generated-index", + "title": "Frontend Development: Building the UI", + "description": "Welcome to the face of the web. In this track, you'll learn how to craft beautiful, responsive, and interactive user interfaces using HTML, CSS, and modern styling techniques. This is where your code becomes a visual reality." + } +} \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/introduction.mdx b/absolute-beginners/full-stack/frontend/introduction.mdx index e345ed2..55b6a8a 100644 --- a/absolute-beginners/full-stack/frontend/introduction.mdx +++ b/absolute-beginners/full-stack/frontend/introduction.mdx @@ -1 +1,56 @@ - \ No newline at end of file +--- +title: "Introduction to Frontend" +sidebar_label: "1. Introduction" +sidebar_position: 1 +description: "Understand what frontend development is and the roles of HTML, CSS, and JavaScript." +--- + +Frontend development is the art and science of building everything a user sees, touches, and experiences in their web browser. It is the bridge between a raw idea and a functional interface. + +At **CodeHarborHub**, we call this the "Visual Side" of the stack. + +## 1. What is the "Frontend"? + +When you visit a website, your browser (like Chrome or Safari) receives files from a server. The frontend is the combination of those files working together to create a smooth experience. + +It involves: +* **Design:** How it looks (Colors, Layout, Typography). +* **Interaction:** What happens when you click or scroll. +* **Performance:** How fast the page loads and feels. +* **Accessibility:** Ensuring everyone, including people with disabilities, can use the site. + +## 2. The Three Pillars of the Web + +Every single website you have ever visited is built using three core technologies. Think of it like building a **House**: + +### HTML (The Skeleton) +**HyperText Markup Language** is the structure. It defines what goes on the page. Is it a heading? A paragraph? An image? Without HTML, there is no content. + +### CSS (The Skin & Style) +**Cascading Style Sheets** make the house look beautiful. It handles the paint, the wallpaper, the furniture placement, and the lighting. Without CSS, the web would be plain black text on a white background. + +### JavaScript (The Brains) +**JavaScript** adds logic and behavior. It’s the wiring that makes the doorbell ring, the lights turn on, and the elevator move. It makes the website interactive. + +## 3. The Modern Frontend Workflow + +Building websites today is more than just typing code. As a frontend developer at **CodeHarborHub**, you will learn to use: + +| Stage | What you'll do | Tools | +| :--- | :--- | :--- | +| **Design** | Plan the layout and colors. | Figma, Adobe XD | +| **Development** | Write the code. | VS Code, Git | +| **Responsive** | Make it work on mobile phones. | Chrome DevTools | +| **Deployment** | Put it on the internet. | GitHub Pages, Vercel | + +## 4. What we will build + +In this track, we aren't just going to read about code—we are going to create. You will progress through: + +1. **Static Pages:** Simple resumes and landing pages using HTML & CSS. +2. **Responsive Layouts:** Websites that look great on an iPhone and a 4K Monitor. +3. **Interactive Apps:** Projects that react to user input using JavaScript. + +:::info The "Inspect" Secret +You can see the frontend code of **any** website right now. Right-click anywhere on this page and select **"Inspect"**. That window shows you the real-time HTML and CSS running this site! +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/mini-projects.mdx b/absolute-beginners/full-stack/frontend/mini-projects.mdx index e345ed2..aee27dc 100644 --- a/absolute-beginners/full-stack/frontend/mini-projects.mdx +++ b/absolute-beginners/full-stack/frontend/mini-projects.mdx @@ -1 +1,79 @@ - \ No newline at end of file +--- +title: "Frontend Mini-Projects" +sidebar_label: "Mini-Projects" +sidebar_position: 10 +description: "Put your frontend skills to the test with these beginner-friendly projects. Build a digital business card, a to-do list, a weather dashboard, and a quiz app to practice HTML, Tailwind CSS, JavaScript, and React." +tags: ["frontend", "projects", "html", "css", "javascript", "react"] +keywords: ["frontend projects", "html project", "css project", "javascript project", "react project", "beginner projects"] +--- + +Congratulations! You've navigated through the core pillars of Frontend development. Now, it's time to build. These projects will help you practice "The Developer Mindset": breaking a large problem into small, solvable tasks. + +## Project 1: The Digital Business Card +**Focus:** *HTML, Tailwind CSS* + +Build a responsive profile card that introduces you to the world. + +* **Requirements:** + * Use a profile image (rounded). + * Include social media links with hover effects. + * Make it responsive: it should look good on a phone and a desktop. +* **Tailwind Challenge:** Use a custom gradient background and a subtle drop shadow (`shadow-xl`). + +## Project 2: Interactive Task Master (To-Do List) +**Focus:** *JavaScript DOM Manipulation / React State* + +The classic developer rite of passage. This project teaches you how to handle user input and update the UI dynamically. + +* **Requirements:** + * An input field to add new tasks. + * A "Delete" button for each task. + * A "Complete" toggle that strikes through the text. +* **Logic Challenge:** Use `localStorage` so your tasks don't disappear when you refresh the page! + +## Project 3: Real-Time Weather Dashboard +**Focus:** *API Integration, Async/Await* + +Connect your frontend to the real world by fetching live weather data. + +* **Requirements:** + * Fetch data from the [OpenWeatherMap API](https://openweathermap.org/api). + * Display the temperature, humidity, and an icon representing the weather. + * Change the background color based on the temperature (e.g., Blue for cold, Orange for hot). +* **Safety Challenge:** Handle "City Not Found" errors gracefully with a user-friendly message. + +## Project 4: The "A Master" Quiz App +**Focus:** *React, State Management* + +Create a multiple-choice quiz that tracks scores and gives feedback. + +* **Requirements:** + * Create an array of objects containing questions and answers. + * Show one question at a time. + * At the end, show the final score and a "Restart" button. +* **UI Challenge:** Add a progress bar at the top that fills up as the user moves through the questions. + +## How to Approach These Projects + +When you start a project at **CodeHarborHub**, follow this workflow: + +1. **Sketch it:** Draw the UI on paper. Identify your **Components**. +2. **HTML/JSX First:** Build the structure without styling. Make sure the buttons and inputs work. +3. **Style it:** Use **Tailwind** to make it look professional. Focus on spacing and typography. +4. **Add the Logic:** Use **JavaScript** or **React Hooks** to make it interactive. +5. **Refactor:** Look at your code. Can you make a function shorter? Can you remove a redundant div? + +## Sharing Your Work + +Don't build in silence! +* **GitHub:** Create a repository for each project. +* **Vercel/Netlify:** Deploy your projects for free so you can share the link in your portfolio. +* **LinkedIn:** Post a screen recording of your working project and tag the **CodeHarborHub** community! + +:::tip Stuck? +If you run into a bug, remember the **CodeHarborHub** motto: "Search, Read, Build." Check the documentation, search on Stack Overflow, and try to solve it before asking for the answer. That's how great engineers are made. +::: + +### What's Next? + +You've conquered the Frontend! You now have the power to build beautiful, interactive interfaces. It's time to go deeper into the "brain" of the web: the Server. In the next section, we'll explore how to create APIs, manage databases, and build the backend logic that powers modern web applications. Get ready to become a full-stack developer! \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/react/_category_.json b/absolute-beginners/full-stack/frontend/react/_category_.json new file mode 100644 index 0000000..044417b --- /dev/null +++ b/absolute-beginners/full-stack/frontend/react/_category_.json @@ -0,0 +1,9 @@ +{ + "label": "React.js", + "position": 2, + "link": { + "type": "generated-index", + "title": "React.js: Modern UI Development", + "description": "Master the world's most popular JavaScript library for building user interfaces. Learn how to break your UI into reusable components, manage state effectively, and build fast, dynamic web applications that feel like native apps." + } +} \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/react/api-integration.mdx b/absolute-beginners/full-stack/frontend/react/api-integration.mdx index e345ed2..9ebea50 100644 --- a/absolute-beginners/full-stack/frontend/react/api-integration.mdx +++ b/absolute-beginners/full-stack/frontend/react/api-integration.mdx @@ -1 +1,159 @@ - \ No newline at end of file +--- +title: "API Integration in React" +sidebar_label: "7. API Integration" +sidebar_position: 7 +description: "Learn how to fetch data from the internet and display it in your React components." +--- + +As a beginner, you might wonder: *"Where does the data on websites come from?"* It usually comes from an **API (Application Programming Interface)**. + +Think of an API like a **waiter** in a restaurant: +1. **You (The React App)** are the customer. +2. **The API (The Waiter)** takes your request. +3. **The Server (The Kitchen)** prepares the data. +4. **The API** brings the data back to your table. + +## 1. The "Fetch" Cycle + +In React, fetching data usually happens in three stages. We use **State** to keep track of these stages so the user knows what's happening. + +1. **Loading State:** "Wait, I'm getting the data..." (Show a spinner). +2. **Success State:** "I got it! Here it is." (Show the data). +3. **Error State:** "Oops, something went wrong." (Show an error message). + +```jsx title="DataFetcher.js" +import { useState, useEffect } from 'react'; +function DataFetcher() { + const [data, setData] = useState(null); // Where we store the data + const [isLoading, setIsLoading] = useState(true); // To show a loading message + const [error, setError] = useState(null); // To show an error message + + useEffect(() => { + fetch('https://api.example.com/data') + .then(response => response.json()) + .then(json => { + setData(json); + setIsLoading(false); + }) + .catch(err => { + setError(err.message); + setIsLoading(false); + }); + }, []); + + if (isLoading) return

Fetching data from the server...

; + if (error) return

Error: {error}

; + + return ( +
+

Fetched Data:

+
{JSON.stringify(data, null, 2)}
+
+ ); +} +``` + +## 2. Using the `fetch()` API + +Modern browsers have a built-in function called `fetch()`. Since fetching data is a "Side Effect" (it happens outside of React's rendering), we always put it inside a **`useEffect`** hook. + +### The Noob-Friendly Pattern: + +```jsx title="UserList.js" +import { useState, useEffect } from 'react'; + +function UserList() { + const [users, setUsers] = useState([]); // Where we store the data + const [isLoading, setIsLoading] = useState(true); // To show a loading message + + useEffect(() => { + // 1. Call the API + fetch('https://jsonplaceholder.typicode.com/users') + .then((response) => response.json()) // 2. Turn response into JSON + .then((data) => { + setUsers(data); // 3. Save data to state + setIsLoading(false); // 4. Turn off loading + }) + .catch((error) => console.error("Error fetching data:", error)); + }, []); // [] means: "Only do this once when the page loads" + + if (isLoading) return

Fetching users from the server...

; + + return ( +
    + {users.map(user => ( +
  • {user.name}
  • + ))} +
+ ); +} +``` + +## 3. Async/Await (The Cleaner Way) + +The `.then()` syntax can get messy. Professional developers prefer **Async/Await** because it reads like normal English. + +```jsx title="UserListAsync.js" +import { useState, useEffect } from 'react'; +const fetchData = async () => { + try { + const response = await fetch('https://api.example.com/data'); + const result = await response.json(); + setData(result); + } catch (error) { + console.log("Something broke:", error); + } +}; +``` + +## 4. Common API Rules for Beginners + +* **The Dependency Array:** Always use an empty array `[]` in `useEffect` for data fetching. If you forget it, your app will fetch data in an **infinite loop**, which can crash the server (or your browser!). +* **Unique Keys:** When you display a list of data using `.map()`, always give the top element a `key={item.id}`. It helps React stay fast. +* **JSON is your friend:** Almost all APIs send data in **JSON** format. It looks just like a JavaScript object. + +```json title="Example API Response" +{ + "id": 1, + "name": "John Doe", + "email": "john.doe@example.com" +} +``` + +## Practice: The Random Joke Generator + +Let's build something fun! We will use a free API to get a random joke. + +```jsx title="JokeApp.js" +import { useState } from 'react'; + +function JokeApp() { + const [joke, setJoke] = useState("Click the button to get a joke!"); + + const getJoke = async () => { + setJoke("🤔 Thinking..."); + const response = await fetch("https://official-joke-api.appspot.com/random_joke"); + const data = await response.json(); + setJoke(`${data.setup} ... ${data.punchline}`); + }; + + return ( +
+

Project: Joke Generator

+

{joke}

+ +
+ ); +} +``` + +:::info Free APIs for Practice +Don't have a backend yet? Use these "Placeholder" APIs to practice: +* **JSONPlaceholder:** Great for fake users, posts, and comments. +* **PokeAPI:** Great for learning how to handle complex data (Pokemon!). +* **OpenWeather:** Great for learning how to use API Keys. +::: + +:::warning Handling "Null" Data +When your page first loads, your state might be `null`. If you try to access `data.name` before the API finishes, your app will crash. Always use **Conditional Rendering** (like `data && data.name`) to stay safe! +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/react/components.mdx b/absolute-beginners/full-stack/frontend/react/components.mdx index e345ed2..46bcb7e 100644 --- a/absolute-beginners/full-stack/frontend/react/components.mdx +++ b/absolute-beginners/full-stack/frontend/react/components.mdx @@ -1 +1,172 @@ - \ No newline at end of file +--- +title: "Components & Props" +sidebar_label: "3. Components & Props" +sidebar_position: 3 +description: "Learn how to build reusable UI building blocks and pass data between them using Props." +--- + +In React, we don't build "pages"—we build **Components**. A component is a small, reusable piece of the user interface. By combining these pieces, you can build complex applications that are easy to maintain and scale. + +## 1. What is a Component? + +Think of a component as a custom HTML element. For example, instead of writing the HTML for a user profile card five times, you create a `` component and reuse it. + +:::info For Example + +Now, instead of writing this multiple times: + +```jsx live +function WelcomeMessage() { + return

Hello, CodeHarborHub Learner!

; +} +``` + +You can create a reusable component: + +```jsx title="WelcomeMessage.js" +function WelcomeMessage() { + return

Hello, CodeHarborHub Learner!

; +} +``` + +And then use it anywhere in your app: + +```jsx title="App.js" +function App() { + return ( +
+ + + +
+ ); +} +``` + +This way, if you want to change the message, you only need to update it in one place! +::: + +There are two types of components in React history, but at **CodeHarborHub**, we focus on the modern standard: **Functional Components**. + +```jsx title="Functional Component" +function Greeting() { + return

Welcome to CodeHarborHub!

; +} +``` + +## 2. Component Composition + +Components can be nested inside other components. This is called **Composition**. You usually have one `App` component at the top, which contains many smaller children. + +```jsx title="App.js" +function Navbar() { + return ; +} + +function App() { + return ( +
+ + +
+ ); +} +``` + +## 3. What are Props? + +Components are even more powerful when they are dynamic. **Props** (short for "properties") allow you to pass data from a parent component to a child component. + +Think of Props like **arguments in a function** or **attributes in an HTML tag**. + +:::info Why "Props"? +The name "Props" comes from the idea of "properties" that you can set on a component, similar to how you set properties on HTML elements (like `class`, `id`, etc.). They are the way we customize and configure our components. +::: + +### How to use Props: + +1. **Pass the prop** in the parent component. +2. **Receive the prop** as an object in the child component function. + +```jsx title="App.js" +// 1. The Child Component +function GreetUser(props) { + return

Welcome, {props.name}!

; +} + +// 2. The Parent Component +function App() { + return ( +
+ + +
+ ); +} +``` + +## 4. Destructuring Props + +To make your code cleaner, developers often "destructure" the props object right in the function signature. This is the standard way we write code at the Hub. + +```jsx title="CourseCard.js" +// Cleaner version using destructuring +function CourseCard({ title, duration }) { + return ( +
+

{title}

+

Time: {duration} hours

+
+ ); +} +``` + +## 5. The "Children" Prop + +Sometimes you want to pass actual JSX or elements into a component, not just strings or numbers. For this, React provides a special prop called `children`. + +```jsx title="Layout.js" +function Layout({ children }) { + return ( +
+
CodeHarborHub
+
{children}
+
+ ); +} + +// Usage + +

This paragraph is passed as 'children'!

+
+``` + +## Practice: Building a Project Card + +Let's build a reusable card for your portfolio projects: + +```jsx title="ProjectCard.js" +function ProjectCard({ name, tech, isCompleted }) { + return ( +
+

{name}

+

Tech Stack: {tech}

+

Status: {isCompleted ? "✅ Finished" : "⏳ In Progress"}

+
+ ); +} + +// In your App.js + + +``` + +:::info Props are Read-Only +A component should never change its own props. They are "immutable." If you need to change data within a component, that’s where **State** comes in! +::: + +:::warning Capitalize Component Names! +In React, component names **must** start with a capital letter (e.g., ``). If you use a lowercase letter (``), React will think it is a standard HTML tag and your code won't work. +::: + +Now that you understand the basics of components and props, you're ready to start building your own reusable UI pieces and passing data around in your React apps! Next, we'll dive into **State** to make our components interactive and dynamic. \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/react/hooks.mdx b/absolute-beginners/full-stack/frontend/react/hooks.mdx index e345ed2..7cd6e1e 100644 --- a/absolute-beginners/full-stack/frontend/react/hooks.mdx +++ b/absolute-beginners/full-stack/frontend/react/hooks.mdx @@ -1 +1,145 @@ - \ No newline at end of file +--- +title: "React Hooks" +sidebar_label: "6. Hooks" +sidebar_position: 6 +description: "Learn the most commonly used React Hooks like useState and useEffect to manage state and side effects." +--- + +Hooks are special functions that let you "hook into" React state and lifecycle features from functional components. At **CodeHarborHub**, we use hooks to build everything from simple counters to complex, data-driven dashboards. + +## 1. The Rules of Hooks + +Before you start "hooking" into React, you must follow these two golden rules: +1. **Only Call Hooks at the Top Level:** Don’t call Hooks inside loops, conditions, or nested functions. +2. **Only Call Hooks from React Functions:** Call them from React functional components or custom Hooks. + +## 2. `useState`: The State Manager + +The most common hook is `useState`. It allows a component to "remember" things like user input, toggle states, or data from an API. + +```jsx title="Counter.js" +import { useState } from 'react'; + +function Counter() { + const [count, setCount] = useState(0); + + return ( +
+

Current Count: {count}

+ +
+ ); +} +``` + +## 3. `useEffect`: Handling Side Effects + +`useEffect` tells React that your component needs to do something *after* rendering. Common examples include: +* Fetching data from an API. +* Manually changing the DOM (like page titles). +* Setting up a subscription or timer. + +```jsx title="DataFetcher.js" +import { useState, useEffect } from 'react'; +function DataFetcher() { + const [data, setData] = useState(null); + + useEffect(() => { + fetch('https://api.example.com/data') + .then(response => response.json()) + .then(json => setData(json)); + }, []); // Empty array means this runs once on mount + + return ( +
+

Fetched Data:

+
{JSON.stringify(data, null, 2)}
+
+ ); +} +``` + +### The Dependency Array + +The second argument to `useEffect` controls when it runs: +* **`[]` (Empty array):** Runs only once (when the component "mounts"). +* **`[value]` (With variables):** Runs every time that specific value changes. +* **No array:** Runs after every single render (use with caution!). + +```jsx title="Timer.js" +import { useState, useEffect } from 'react'; + +function Timer() { + const [seconds, setSeconds] = useState(0); + + useEffect(() => { + const interval = setInterval(() => { + setSeconds(prev => prev + 1); + }, 1000); + + // Cleanup: Stops the timer when the component is removed + return () => clearInterval(interval); + }, []); // Empty array = run once on mount + + return

Time spent: {seconds}s

; +} +``` + +## 4. `useRef`: Accessing the DOM + +Sometimes you need to reach out and touch a DOM element directly (e.g., to focus an input field or measure an element's size). For this, we use `useRef`. + +```jsx title="TextInputWithFocusButton.js" +import { useRef } from 'react'; + +function TextInputWithFocusButton() { + const inputEl = useRef(null); + + const onButtonClick = () => { + // Directly focus the text input + inputEl.current.focus(); + }; + + return ( + <> + + + + ); +} +``` + +## 5. Custom Hooks + +One of the coolest features of React is that you can create your own hooks! This allows you to extract component logic into reusable functions. Custom hooks **must** start with the word `use`. + +*Example: `useFetch`, `useLocalStorage`, `useWindowSize`.* + +## Practice: The Document Title Updater + +Let's build a component that updates the browser tab title every time a counter changes. + +```jsx title="TitleUpdater.js" +import React, { useState, useEffect } from 'react'; + +function TitleUpdater() { + const [count, setCount] = useState(0); + + useEffect(() => { + document.title = `Clicked ${count} times`; + }, [count]); // Only update title when 'count' changes + + return ( +
+

Check your browser tab!

+ +
+ ); +} +``` + +:::info Functional Updates +When your new state depends on the old state (like a counter), it’s safer to use the functional update pattern: `setCount(prevCount => prevCount + 1)`. This ensures you are always using the most recent value! +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/react/intro.mdx b/absolute-beginners/full-stack/frontend/react/intro.mdx index e345ed2..1c7a919 100644 --- a/absolute-beginners/full-stack/frontend/react/intro.mdx +++ b/absolute-beginners/full-stack/frontend/react/intro.mdx @@ -1 +1,62 @@ - \ No newline at end of file +--- +title: "Introduction to React" +sidebar_label: "1. Intro to React" +sidebar_position: 1 +description: "Understand the core concepts of React.js and why it is the industry standard for modern web apps." +--- + +**React** is a JavaScript **library** for building user interfaces. Created by Facebook (Meta), it has become the most popular choice for frontend developers because it makes building complex, interactive websites predictable and efficient. + +## 1. Why React? (The Problem it Solves) + +In traditional "Vanilla" JavaScript, if you want to update a piece of text on a page, you have to: +1. Find the element in the DOM. +2. Manually change its content. +3. Keep track of those changes everywhere else. + +As your app grows, this becomes a nightmare to manage. **React** solves this by using a **Declarative** approach. You just describe what the UI should look like for a specific state, and React handles the "how" of updating the screen. + +## 2. Key Concepts of React + +To master React at **CodeHarborHub**, you need to understand these three pillars: + +### Components +Imagine building a house with LEGO bricks. Each brick is a **Component**. A component is a self-contained piece of code (like a Navbar, a Button, or a User Profile) that can be reused across your entire application. + +### JSX (JavaScript XML) +JSX allows us to write HTML-like code directly inside our JavaScript. It makes the structure of our components easy to see and write. + +```jsx +const Welcome = () => { + return

Hello, CodeHarborHub!

; +}; +``` + +### The Virtual DOM +Updating the real browser DOM is slow. React creates a lightweight "copy" called the **Virtual DOM**. When something changes: +1. React updates the Virtual DOM first. +2. It compares the Virtual DOM with the real DOM (Diffing). +3. It only updates the *specific* parts of the real DOM that actually changed. This makes React incredibly fast! + +## 3. Library vs. Framework + +Is React a library or a framework? At **CodeHarborHub**, we clarify the difference: + +* **Library (React):** A collection of tools. You are the boss. You decide which router or state management tool to plug in. (React = "The Engine"). +* **Framework (Angular/Next.js):** A complete structure. It tells you exactly how to organize your files and what tools to use. (Framework = "The whole Car"). + +## 4. Setting the Stage + +To use React, you need to have **Node.js** and **npm** installed on your computer. Modern React apps are usually created using a "Build Tool" like **Vite**, which sets up everything for you in seconds. + +### The React Ecosystem: +| Tool | Purpose | +| :--- | :--- | +| **Vite** | Blazing fast build tool to start projects. | +| **React Router** | For navigating between pages. | +| **Tailwind CSS** | For styling your components quickly. | +| **Axios/Fetch** | For getting data from APIs. | + +:::info Thinking in Components +Before you start coding a React project, grab a pen and paper. Draw boxes around the different parts of the design. Each box is a potential component. This "Component Architecture" is the secret to clean React code! +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/react/jsx-basics.mdx b/absolute-beginners/full-stack/frontend/react/jsx-basics.mdx new file mode 100644 index 0000000..ef0a7f5 --- /dev/null +++ b/absolute-beginners/full-stack/frontend/react/jsx-basics.mdx @@ -0,0 +1,134 @@ +--- +title: "JSX Basics" +sidebar_label: "2. JSX Basics" +sidebar_position: 2 +description: "Learn the syntax rules of JSX and how to embed JavaScript logic into your HTML structure." +--- + +**JSX** is a syntax extension for JavaScript. It looks like HTML, but it has the full power of JavaScript behind it. In React, we use JSX to describe what the UI should look like. It allows us to write HTML-like code directly in our JavaScript files, making it easier to visualize the structure of our components. + +## 1. Why JSX? + +Instead of using `document.createElement()` or complex DOM manipulation, JSX lets you write the UI in a way that is familiar and easy to read. + +For example, instead of writing: + +```javascript +const element = React.createElement('h1', null, 'Hello, CodeHarborHub!'); +``` + +You can simply write: + +```jsx +const element =

Hello, CodeHarborHub!

; +``` + +This is much more intuitive and closely resembles the final HTML output. + +While the browser doesn't understand JSX natively, tools like **Babel** compile it into standard JavaScript that the browser can execute. + +## 2. The Rules of JSX + +To keep your React apps running smoothly at **CodeHarborHub**, you must follow these three fundamental rules: + +### 1. Return a Single Root Element +A component must return **one** single parent element. If you have multiple elements, wrap them in a `
` or a **Fragment** (`<>...`). + +```jsx +// This will throw an error +return ( +

Hello

+

Welcome to the hub!

+); + +// This is correct +return ( + <> +

Hello

+

Welcome to the hub!

+ +); +``` + +### 2. Close All Tags +In HTML, some tags like `` or `
` don't need a closing tag. In JSX, **every tag must be closed**. +* `
` +* `` +* `` + +### 3. camelCase Naming +Since JSX is closer to JavaScript than HTML, we use camelCase for attributes. +* `class` becomes **`className`** +* `onclick` becomes **`onClick`** +* `tabindex` becomes **`tabIndex`** + +## 3. Embedding JavaScript in JSX + +The real power of JSX is that you can drop any JavaScript expression inside your "HTML" by using **curly braces `{ }`**. + +### Using Variables +```jsx +const name = "A Master"; + +function Welcome() { + return

Welcome back, {name}!

; +} +``` + +### Dynamic Logic +You can perform math or call functions inside the braces: +```jsx +const user = { firstName: 'Ajay', lastName: 'Dhangar' }; + +return ( +

User score: {10 + 25}

+

Full Name: {user.firstName + " " + user.lastName}

+); +``` + +## 4. Conditional Rendering + +You can't put `if/else` statements directly inside `{ }`, so we use **Ternary Operators** or the **Logical &&** operator. + +```jsx +const isLoggedIn = true; + +return ( +
+ {isLoggedIn ? : } + + {/* Only show this if the user is a founder */} + {isFounder &&

Welcome, CEO!

} +
+); +``` + +## Practice: The Greeting Component + +Try creating a component that displays a different message based on the time of day: + +```jsx +function Greeting() { + const hours = new Date().getHours(); + let timeOfDay; + + if (hours < 12) { + timeOfDay = "Morning"; + } else if (hours >= 12 && hours < 17) { + timeOfDay = "Afternoon"; + } else { + timeOfDay = "Evening"; + } + + return ( +
+

Good {timeOfDay}, Learner!

+

It's currently {hours} o'clock.

+
+ ); +} +``` + +:::info Expressions vs. Statements +Remember: You can only put **Expressions** (things that result in a value) inside curly braces. You cannot put **Statements** (like a `for` loop or a `switch` case) inside them. +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/react/performance.mdx b/absolute-beginners/full-stack/frontend/react/performance.mdx index e345ed2..0603c7d 100644 --- a/absolute-beginners/full-stack/frontend/react/performance.mdx +++ b/absolute-beginners/full-stack/frontend/react/performance.mdx @@ -1 +1,83 @@ - \ No newline at end of file +--- +title: "React Performance Optimization" +sidebar_label: "8. Performance" +sidebar_position: 8 +description: "Learn how to optimize your React applications for speed and efficiency using memoization and best practices." +--- + +React is fast by default, but as you add more components and complex data, you might notice your app "lagging." Performance optimization in React is mostly about one thing: **Reducing Unnecessary Re-renders.** + +## 1. Why do components re-render? + +In React, a component re-renders when: +1. Its **Internal State** changes. +2. Its **Props** change. +3. Its **Parent** re-renders. + +At **CodeHarborHub**, we teach you to identify when a component is rendering too much. If a component's output hasn't changed, it shouldn't waste energy re-rendering. + +## 2. `React.memo`: Skipping Re-renders + +If you have a child component that receives the same props every time, but its parent keeps re-rendering, you can wrap the child in `React.memo`. This tells React: "Only re-render this child if its props actually change." + +```jsx title="ChildComponent.js" +import React from 'react'; + +const ChildComponent = React.memo(({ name }) => { + console.log("Child rendered!"); + return

Welcome, {name}!

; +}); +``` + +## 3. `useMemo`: Remembering Expensive Calculations + +Sometimes you have a function that takes a long time to run (like filtering a list of 10,000 items). You don't want to run that function on every single render. `useMemo` "remembers" (memoizes) the result. + +```jsx title="ProductList.js" +import { useMemo } from 'react'; + +function ProductList({ products, searchToken }) { + // Only re-calculates if products or searchToken change + const filteredProducts = useMemo(() => { + return products.filter(p => p.name.includes(searchToken)); + }, [products, searchToken]); + + return
{/* Render filteredProducts */}
; +} +``` + +## 4. `useCallback`: Preventing Function Recreation + +In JavaScript, functions are objects. Every time a component renders, any function defined inside it is created as a "new" function. This can break `React.memo` for children. `useCallback` keeps the same function instance between renders. + +```jsx title="Parent.js" +import { useCallback } from 'react'; + +function Parent() { + const [count, setCount] = useState(0); + + // This function won't change unless count changes + const handleClick = useCallback(() => { + console.log("Button clicked!"); + }, []); + + return ; +} +``` + +## 5. Key Best Practices for Speed + +* **Lazy Loading:** Don't load the entire app at once. Use `React.lazy` to load components only when they are needed (e.g., loading the "About" page only when the user clicks it). +* **Windowing/Virtualization:** If you have a list of 1,000 items, don't render 1,000 HTML elements. Only render the 10 that are currently visible on the screen. +* **Keep State Local:** Don't put everything in a global state (like Redux or Context) if only one small component needs it. + +## Practice: Using the React Profiler + +1. Open your React app in Chrome. +2. Open **Developer Tools** and go to the **Profiler** tab. +3. Click **Record**, interact with your app, and click **Stop**. +4. Look for "flame charts"—long bars mean a component took a long time to render. Identify which component is causing the bottleneck! + +:::warning Don't Over-Optimize! +Optimization has a cost (it makes code harder to read). As a rule at the Hub: **Build it first, then optimize if it feels slow.** Most small apps don't need `useMemo` or `useCallback` everywhere. +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/react/props-state.mdx b/absolute-beginners/full-stack/frontend/react/props-state.mdx index e345ed2..f36ea61 100644 --- a/absolute-beginners/full-stack/frontend/react/props-state.mdx +++ b/absolute-beginners/full-stack/frontend/react/props-state.mdx @@ -1 +1,101 @@ - \ No newline at end of file +--- +title: "Props vs. State" +sidebar_label: "4. Props vs. State" +sidebar_position: 4 +description: "Master the difference between external data (Props) and internal data (State) in React." +--- + +In React, data flows through your application. To build dynamic interfaces, you need to understand the two ways a component handles that data: **Props** and **State**. + +## 1. The Core Difference + +Think of a **Component** like a **Digital Watch**: +* **Props:** The color of the strap, the brand name, or the material. These are assigned when the watch is made and don't change from the watch's perspective. +* **State:** The current time. It changes every second, and the watch is responsible for updating its own display to show the new time. + +| Feature | Props (Properties) | State | +| :--- | :--- | :--- | +| **Source** | Passed from a Parent component. | Defined inside the component itself. | +| **Mutability** | **Read-Only** (Immutable). | **Can be changed** (Mutable). | +| **Purpose** | Configuration & Data sharing. | Interactivity & Dynamic data. | +| **Trigger** | Changes when the Parent updates. | Changes when user interacts (clicks, types). | + +## 2. Deep Dive: Props + +Props are like function arguments. They allow a parent to "talk" to its children. + +```jsx title="App.js" +// Child Component +function UserBadge({ username }) { + // ❌ props.username = "NewName"; // This would throw an error! + return
{username}
; +} + +// Parent Component +function App() { + return ; +} +``` + +## 3. Deep Dive: State + +State is a component's "private memory." When state changes, React automatically re-renders the component to show the new data. We use the `useState` Hook to manage this. + +```jsx +import { useState } from 'react'; + +function LikeButton() { + // [currentValue, functionToUpdateValue] + const [likes, setLikes] = useState(0); + + return ( + + ); +} +``` + +## 4. When to use which? + +Ask yourself: **"Does this data need to change over time within this component?"** + +* **Use Props if:** The data is just being "displayed" or was decided by the parent (e.g., a button's text, a user's ID). +* **Use State if:** The data changes due to user input, an API response, or a timer (e.g., text in an input field, a toggle switch, a shopping cart count). + +## 5. One-Way Data Flow + +In React, data moves in **one direction**: from Top to Bottom (Parent to Child). + +1. A Parent holds the **State**. +2. The Parent passes that state down to a Child as a **Prop**. +3. If the Child needs to change the data, the Parent passes a **Function** (as a prop) that the child can call to update the parent's state. + +## Practice: The Theme Switcher + +Let's see them working together. The `App` holds the state (the theme), and the `Button` displays it via props. + +```jsx title="App.js" +function ThemeDisplay({ currentTheme }) { + return

The current theme is: {currentTheme}

; +} + +function App() { + const [theme, setTheme] = useState("Light"); + + const toggleTheme = () => { + setTheme(theme === "Light" ? "Dark" : "Light"); + }; + + return ( +
+ {/* Passing state as a prop */} + +
+ ); +} +``` + +:::info Lift the State Up +If two child components need to share the same data, don't try to pass data between them. Move the state into their **common parent** and pass it down to both as props. This is called "Lifting State Up." +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/frontend/react/routing.mdx b/absolute-beginners/full-stack/frontend/react/routing.mdx index e345ed2..15cf9bb 100644 --- a/absolute-beginners/full-stack/frontend/react/routing.mdx +++ b/absolute-beginners/full-stack/frontend/react/routing.mdx @@ -1 +1,117 @@ - \ No newline at end of file +--- +title: "React Router Basics" +sidebar_label: "5. React Router" +sidebar_position: 5 +description: "Learn how to create navigation and multiple pages in a Single Page Application (SPA)." +--- + +By default, React only shows one "page" (the `App` component). To build a site with an **About** page, a **Contact** page, and a **Dashboard**, we use a library called **React Router**. + +This allows us to change the URL in the browser without the page actually refreshing! + +## 1. Installation + +React Router is an external library. To use it in your CodeHarborHub project, install it via npm: + +```bash +npm install react-router-dom +``` + +## 2. The Core Components + +To set up routing, you need to understand these four components: + +1. **``**: The parent wrapper that enables routing. +2. **``**: A container that looks through all its children to find the best match for the current URL. +3. **``**: Connects a specific **Path** (like `/about`) to a **Component** (like ``). +4. **``**: The React version of an `` tag. It changes the URL without refreshing the page. + +## 3. Basic Setup Example + +Here is how you organize your `App.js` to handle multiple pages: + +```jsx title="App.js" +import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'; +import Home from './pages/Home'; +import About from './pages/About'; + +function App() { + return ( + + + + + } /> + } /> + + + ); +} +``` + +In this example: + +* The `` wraps the entire app to enable routing. +* The `