diff --git a/absolute-beginners/frontend-beginner/react/_category_.json b/absolute-beginners/frontend-beginner/react/_category_.json new file mode 100644 index 0000000..e322f48 --- /dev/null +++ b/absolute-beginners/frontend-beginner/react/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "React", + "position": 6, + "link": { + "type": "generated-index", + "description": "Master the fundamentals of React.js. Learn about components, JSX, props, and state to build modern, interactive web applications." + } +} \ No newline at end of file diff --git a/absolute-beginners/frontend-beginner/react/hooks-use-state.mdx b/absolute-beginners/frontend-beginner/react/hooks-use-state.mdx new file mode 100644 index 0000000..6bd76b2 --- /dev/null +++ b/absolute-beginners/frontend-beginner/react/hooks-use-state.mdx @@ -0,0 +1,112 @@ +--- +sidebar_position: 6 +title: "Hooks: Powering Up with useState" +sidebar_label: "6. The useState Hook" +description: "Learn how to make your components interactive by managing state with the useState hook." +--- + +Imagine you are building a **Counter** app. You have a button that says "Click Me," and you want a number on the screen to go up every time you click it. + +In plain JavaScript, you would have to find the HTML element and manually change its text. In React, we use the `useState` hook to tell React: *"Hey, keep track of this number, and whenever it changes, update the screen for me automatically!"* + +## 🤔 What is a Hook? + +Hooks are special functions that let you "hook into" React features. Think of them as **Power-Ups** for your components. +* **Regular Function:** Just displays data. +* **Function with Hooks:** Can remember things, perform actions, and react to user input. + +## The Anatomy of useState + +When you use `useState`, it always gives you back **two things** in an array: + +1. **The Current State:** The current value stored in memory (e.g., `0`). +2. **The Setter Function:** A special function used to update that value (e.g., `setCount`). + +```javascript +const [count, setCount] = useState(0); +``` + +* `count` is the value. +* `setCount` is the remote control to change that value. +* `0` is the starting point (Initial State). + +## Live Interactive: Your First State + +Try clicking the button below! Watch how React instantly re-renders the component every time the `count` changes. + +```jsx live +function App() { + // 1. Import (implicitly) and initialize state + // We start at 0 + const [count, setCount] = React.useState(0); + + return ( +
+

The Click-O-Meter

+

{count}

+ + + + +
+ ); +} + +``` + +## The Golden Rule of State + +**Never change state directly:** +* `count = count + 1` (React won't notice, and the screen won't update). +* `setCount(count + 1)` (React notices, updates the memory, and refreshes the UI). + +:::tip Want to dive deeper? + +`useState` is just the beginning! React has many other hooks like `useEffect` (for fetching data) and `useContext` (for global themes). + +👉 **Explore the full Hook library:** For a detailed breakdown of all React Hooks, check out our [Comprehensive Hooks Guide](https://codeharborhub.github.io/tutorial/category/hooks). + +::: + +## Summary Checklist + +* [x] I know that Hooks start with the word `use`. +* [x] I understand that `useState` returns a value and a function to change it. +* [x] I know that I must use the **Setter Function** to update the UI. +* [x] I successfully built a working counter! \ No newline at end of file diff --git a/absolute-beginners/frontend-beginner/react/index.mdx b/absolute-beginners/frontend-beginner/react/index.mdx deleted file mode 100644 index e345ed2..0000000 --- a/absolute-beginners/frontend-beginner/react/index.mdx +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/absolute-beginners/frontend-beginner/react/intro-to-react.mdx b/absolute-beginners/frontend-beginner/react/intro-to-react.mdx new file mode 100644 index 0000000..bfcf1a3 --- /dev/null +++ b/absolute-beginners/frontend-beginner/react/intro-to-react.mdx @@ -0,0 +1,143 @@ +--- +sidebar_position: 1 +title: "Why React? The Smart Way to Build" +sidebar_label: "1. Intro to React" +description: "A beginner's guide to why React is the world's favorite tool for building websites." +--- + +Welcome to the **React** era! If you've already learned HTML, CSS, and JavaScript, you might be wondering: *"Why do I need a library? Can't I just use plain JavaScript?"* + +The answer is: **Efficiency.** + +In plain JavaScript, if you wanted to update a user's notification count, you would have to manually find the element, change the text, and make sure everything else on the page didn't break. In React, you just change the **Data**, and React magically updates the **UI** for you. + +:::note +If HTML is the **Skeleton** and JavaScript is the **Brain**, then **React** is the **Architect**. + +React is a JavaScript library created by Facebook to make building user interfaces (UIs) easier, faster, and more organized. Instead of telling the browser every tiny step to take, you just describe what you want the screen to look like. +::: + +## The Mental Shift: How React Thinks + +React acts like a **Smart Assistant**. Instead of you giving "Step-by-Step" instructions (Imperative), you just describe what you want the final result to look like (Declarative). + +### The Visualization: Traditional vs. React + +```mermaid +graph TD + subgraph "Traditional Way (Harder)" + A[Data Changes] --> B[Find
HTML Element] + B --> C[Manually
Update Text] + C --> D[Check if
other parts broke] + end + + subgraph "React Way (Smarter)" + E[Data Changes] --> F{React Virtual DOM} + F -->|Only updates
what changed| G[UI Updates
Instantly] + end +``` + +## The "Big Three" Features + +Why did React win the "Web Library Wars"? Because of these three superpowers: + +### 1. Components (The LEGO Mindset) + +In React, you don't build "Pages." You build **Components**. A Navbar is a component. A Button is a component. You build them once and reuse them everywhere. + +* **Benefit:** Fix a bug in the "Button" component, and it's fixed across your entire website instantly! + +:::info 🧱 The Lego Mindset: Components + +The biggest shift in React is thinking in **Components**. + +Instead of one giant `index.html` file, you build small, independent pieces of code. You can reuse these pieces anywhere, just like LEGO bricks. + +```mermaid +graph TB + subgraph "Your Website" + A[Navbar] + B[Sidebar] + C[Main Feed] + D[Footer] + end + + C --> E[Post Card] + C --> F[Post Card] + C --> G[Post Card] + + E --> H[Like Button] + E --> I[Comment Box] +``` +::: + +### 2. The Virtual DOM (The Fast Copy) + +React keeps a lightweight "Ghost Copy" of your website in its memory. + +* When something changes, React compares the "Ghost Copy" with the "Real Page." +* It finds the **exact** spot that changed and only updates that tiny piece. +* **Analogy:** If you get a haircut, React doesn't replace your whole body; it just updates your hair! + +:::info The Virtual DOM (in other way) +React keeps a "hidden copy" of your website in its memory. This is called the **Virtual DOM**. + +When something changes, React follows these steps: +1. It updates the **Virtual DOM** (which is lightning fast). +2. It compares the Virtual DOM to the **Real DOM** (the one the user sees). +3. It **only** changes the tiny piece that is different. + +```mermaid +graph TD + A[Data Changes] --> B[Update Virtual DOM] + B --> C[Compare with Real DOM] + C --> D{What changed?} + D -->|Only the Button| E[Update Button Only] + D -->|Whole Page| F[Old Way: Refresh Everything] + style E fill:#00d8ff,stroke:#333,stroke-width:2px,color:#333 +``` + +::: + +### 3. Declarative UI (The Menu) + +React is like a restaurant. You look at the menu and say, *"I want a Burger."* You don't go into the kitchen and tell the chef how to flip the patty. You describe the **State** (the burger), and React serves it. + +## When should you use React? + +You don't need React for a simple one-page resume. But you **definitely** need it for: + +* **Social Media:** (Like/Comment counts updating live). +* **Dashboards:** (Graphs and data changing in real-time). +* **E-commerce:** (Adding items to a cart without refreshing the page). + +## Why Beginners Love React + +1. **Speed:** Your apps feel "snappy" because they don't refresh the whole page. +2. **Reusability:** Write a `Button` component once, use it 100 times. +3. **Job Demand:** Almost every modern tech company uses React. Learning this opens doors to professional careers. + + +:::tip Vocabulary Check +**SPA (Single Page Application):** A website that feels like a desktop app because it never refreshes the page while you click around. React is the king of SPAs! +::: + +## Quick Knowledge Check + +| Feature | Plain JS (Vanilla) | React.js | +| --- | --- | --- | +| **Updates** | Slow (Re-renders whole sections) | Fast (Only updates changed parts) | +| **Logic** | Manual (You do everything) | Automated (React handles the DOM) | +| **Code** | Can get messy (Spaghetti) | Organized (Components) | + +## Summary Checklist + +* [x] I understand that React is for building **User Interfaces (UI)**. +* [x] I know that **Components** are reusable building blocks. +* [x] I understand the **Virtual DOM** makes websites feel fast. +* [x] I'm ready to stop writing "Pages" and start building "Components." + +:::tip Fun Fact / info +* React is a free and open-source JavaScript library for building user interfaces (UIs), particularly for single-page applications. It is developed and maintained by Meta (formerly Facebook) and a large community of developers and companies. +* React was created by **Jordan Walke**, a software engineer at Facebook. It was first used on Facebook’s Newsfeed in 2011 and later on Instagram! +::: \ No newline at end of file diff --git a/absolute-beginners/frontend-beginner/react/jsx-syntax.mdx b/absolute-beginners/frontend-beginner/react/jsx-syntax.mdx new file mode 100644 index 0000000..05c43ab --- /dev/null +++ b/absolute-beginners/frontend-beginner/react/jsx-syntax.mdx @@ -0,0 +1,163 @@ +--- +sidebar_position: 4 +title: "JSX: JavaScript + XML" +sidebar_label: "4. JSX Syntax" +description: "Learn the syntax that allows you to write HTML-like code inside your JavaScript." +--- + +**JSX** stands for JavaScript XML. It is a syntax extension for JavaScript that allows you to write code that looks like HTML directly inside your React components. + +Think of JSX as a **Translation Layer**. It allows you to describe what the UI should look like using a familiar HTML-like language, while still having the full power of JavaScript behind it. + +## Why not just use regular HTML? + +In the old way, your **Content** (HTML) and your **Logic** (JavaScript) lived in separate houses. They had to shout across the street to talk to each other. + +With **JSX**, they live in the same room. This makes building interactive features much faster and easier to manage. + +## The 3 Golden Rules of JSX + +To keep the "React Engine" running smoothly, you must follow these three rules: + +### 1. The "One Parent" Rule + +A component must return a **single** parent element. You cannot return two `
` tags side-by-side. + + + + ```jsx + return ( +

Hello

+

Welcome to CodeHarborHub

+ ); + ``` +
+ + Wrap them in a `
` or a **Fragment** `<>...` (an invisible container). + + ```jsx + return ( + <> +

Hello

+

Welcome to CodeHarborHub

+ + ); + ``` + + + +### 2. Close All Tags + +In HTML, you might forget to close an `` or a `
`. In JSX, **every tag must be closed**, or the code will crash. + +* `` +* `
` + +### 3. CamelCase Everything + +Since JSX is closer to JavaScript than HTML, we use camelCase for attributes. + +* Use `className` instead of `class`. +* Use `tabIndex` instead of `tabindex`. +* Use `onClick` instead of `onclick`. + +## The Power of Curly Braces `{ }` + +This is where the magic happens. Any code inside `{ curly braces }` is treated as **Real JavaScript**. This allows you to bring your data into your HTML. + +```jsx live +function Profile() { + const userName = "Ajay"; + const status = "Pro Developer"; + + return ( +
+

User: {userName}

+

Status: {status.toUpperCase()}

+

Calculation: 2 + 2 = {2 + 2}

+
+ ); +} + +``` + +## Styling in JSX + +In regular HTML, you write styles as a long string: `style="color: blue; font-size: 20px;"`. In JSX, we do things differently. Styles are treated as **JavaScript Objects**. + +### 1. The "Double Curly" Secret `{{ }}` + +When you see `style={{ ... }}`, it’s not a special React command. It’s actually two things happening at once: + +* **The Outer Braces `{ }`:** These tell JSX, "Hey, get ready! I’m about to write some JavaScript." +* **The Inner Braces `{ }`:** These create the **JavaScript Object** that holds your CSS rules. + +### 2. CamelCase Properties + +Since we are writing JavaScript, we can't use dashes (like `background-color`). Instead, we use **camelCase**. + +* `background-color` becomes **`backgroundColor`** +* `font-size` becomes **`fontSize`** +* `margin-top` becomes **`marginTop`** + +### Live Interactive Example + +Try changing the `backgroundColor` to `"gold"` or the `padding` to `"20px"` in the editor below to see it update instantly! + +```jsx live +function StyledComponent() { + // We are passing an object directly into the style attribute + return ( +
+ Hello! I am a styled box created with Inline JSX! +
+ ); +} + +``` + +### Clean Code Tip: Using Style Objects + +If you have a lot of styles, your JSX can look messy. A better way is to define your style object **outside** of your return statement. This makes your code much easier to read and maintain. + +```jsx live +function ProfileCard() { + // 1. Define the style object + const cardStyle = { + color: 'white', + backgroundColor: '#333', + padding: '20px', + borderRadius: '10px', + boxShadow: '0 4px 8px rgba(0,0,0,0.2)' + }; + + // 2. Reference the object in your JSX + return ( +
+

User Profile

+

This card is styled using a constant object.

+
+ ); +} + +``` + +## Summary Checklist + +* [x] I know that JSX is "HTML inside JavaScript." +* [x] I remember to use `className` instead of `class`. +* [x] I always wrap my tags in a single parent (or Fragment). +* [x] I use `{ }` whenever I want to use a JavaScript variable or math. + +:::tip Top Secret +Browsers cannot read JSX. Behind the scenes, a tool called **Babel** takes your JSX and converts it into pure JavaScript functions that the browser understands! +::: \ No newline at end of file diff --git a/absolute-beginners/frontend-beginner/react/props-and-state.mdx b/absolute-beginners/frontend-beginner/react/props-and-state.mdx new file mode 100644 index 0000000..e07079e --- /dev/null +++ b/absolute-beginners/frontend-beginner/react/props-and-state.mdx @@ -0,0 +1,194 @@ +--- +sidebar_position: 5 +title: "Props vs. State: The Dynamic Duo" +sidebar_label: "5. Props & State" +description: Learn how to pass data to components and how to handle data that changes. +--- + +In React, data flows like water. To build interactive apps, you need to understand the two ways components handle data: **Props** and **State**. + +## 1. Props (Properties) +**Props** are like "Arguments" for a function. They allow a parent component to pass information down to its children. + +* **Analogy:** Think of a **User Profile Card**. The card is the component, but the *name*, *bio*, and *photo* are passed into it. +* **The Rule:** Props are **Read-Only**. A child component cannot change the props it receives; it can only display them. + +```jsx title="App.js" +// The Child Component +function WelcomeMessage(props) { + return

Hello, {props.name}!

; +} + +// The Parent Component +function App() { + return ( +
+ + +
+ ); +} +``` + +## 2. State (The Component's Memory) + +**State** is data that lives *inside* a component and can **change** over time. When state changes, React automatically re-renders the component to show the new data. + +* **Analogy:** Think of a **Light Switch**. The switch is the component, and the "On/Off" status is its **State**. +* **The Rule:** State is **Private**. Only the component that owns the state can change it. + +## The Comparison Table + +| Feature | Props (The DNA) | State (The Mood) | +| --- | --- | --- | +| **Origin** | Passed from a Parent | Created inside the Component | +| **Changeable?** | No (Read-Only) | Yes (Using `setState`) | +| **Purpose** | To configure the component | To handle interactivity | + +## Seeing them together: The "Like Button" + +Imagine a "Like Button" on a social media post. + +1. The **Color** of the button might be a **Prop** (passed by the theme). +2. Whether the button is **Clicked** or not is **State** (it changes when the user taps it). + +```mermaid +graph TD + Parent[App] -- "Passes Theme='Blue'" --> Child[LikeButton] + subgraph Child [LikeButton Component] + S[State: Liked=False] -- "User Clicks" --> S2[State: Liked=True] + end + S2 --> UI[Button turns Blue & Filled] + +``` + +## Live Interaction: Props in Action + +Try changing the `name` or `color` in the code below to see how props update the UI! + +```jsx live +function App() { + // 1. Define the Child Component inside the App for the Live Editor + const Greeting = (props) => { + return ( +
+

Welcome, {props.name}!

+

Your current theme color is: {props.color}

+
+ ); + }; + + // 2. The Parent returns the final UI + return ( +
+ + +
+ ); +} +``` + +:::info 📝 Note on the Live Editor +In this tutorial's Live Code Block, we define the Greeting component inside the App function. This is necessary because the live playground needs everything in one scope to render properly. + +> In a real-world React project, you would usually put `Greeting` and `App` in separate files. However, to make this **Live Playground** work, we have placed both components in one view so they can talk to each other instantly. + +### Try it Yourself! +* Change `name="Future Coder"` to your own name. +* Change `color="crimson"` to `"gold"` or `"forestgreen"`. + +```jsx title="App.js" +const Greeting = (props) => { + return ( +
+

Welcome, {props.name}!

+

Your current theme color is: {props.color}

+
+ ); +}; + +function App() { + return ( +
+ + +
+ ); +} +``` +::: + +:::note 🌟 Best Practice (Real World) +In a real professional project (like a large app), you should never define a component inside another component. Instead: + +Separate Files: Create a file called `Greeting.jsx`. + +Export/Import: Export the Greeting and import it into your `App.jsx`. + +Performance: Defining components outside ensures React doesn't "re-create" the child component every time the parent updates, making your app significantly faster! +::: + +### Professional Best Practice: Import & Export + +In a real-world project at **CodeHarborHub**, you wouldn't keep all your components in one file. That would get messy! Instead, we put each component in its own file and use `import` and `export`. + +#### 1. The Child File (`Greeting.js`) + +We create the component and "Export" it so other files can use it. + +```jsx title="Greeting.js" +export default function Greeting(props) { + return ( +
+

{props.name}

+
+ ); +} + +``` + +#### 2. The Parent File (`App.js`) + +We "Import" the child component and use it in our UI. + +```jsx title="App.js" +import Greeting from './Greeting'; // Importing the child + +function App() { + return ( +
+ +
+ ); +} +``` + +:::info Why use separate files? + +1. **Readability:** Your `App.js` stays small and easy to read. +2. **Teamwork:** One developer can work on the `Navbar.js` while another works on the `Footer.js` without touching the same file. +3. **Organization:** Just like folders on your computer, separate files help you find your code faster as your project grows. +::: + +## Summary Checklist + +* [x] I know that **Props** are like inputs passed from a parent. +* [x] I understand that **Props** should never be changed by the child. +* [x] I know that **State** is used for data that changes (like counters or forms). +* [x] I understand that when **State** changes, React updates the screen. \ No newline at end of file diff --git a/absolute-beginners/frontend-beginner/react/react-challenge.mdx b/absolute-beginners/frontend-beginner/react/react-challenge.mdx new file mode 100644 index 0000000..f29f8da --- /dev/null +++ b/absolute-beginners/frontend-beginner/react/react-challenge.mdx @@ -0,0 +1,115 @@ +--- +sidebar_position: 7 +title: "Final Challenge: The Profile Switcher" +sidebar_label: "7. React Challenge" +description: "Put your React skills to the test by building an interactive Profile Card Switcher." +--- + +You’ve learned the theory; now it’s time for the "Proof of Skill." Your mission is to build a React app that allows a user to switch between different developer profiles with the click of a button. + +## The Mission Blueprint + +To complete this challenge, you will need to: +1. **Create a Component** that accepts `name`, `role`, and `color` as **Props**. +2. **Use State** to keep track of which user is currently selected. +3. **Use Event Listeners** (`onClick`) to update the state. + +## The Starter Code + +Copy this code into your local environment or play with it right here in the live editor. Your goal is to understand how the data flows from the buttons into the state, and then down into the props. + +```jsx live +function App() { + // 1. DATABASE: An array of user objects + const users = [ + { id: 1, name: "Ajay", role: "Frontend Master", color: "#61dafb" }, + { id: 2, name: "Sanya", role: "UI/UX Queen", color: "#ff6b6b" }, + { id: 3, name: "CodeHarborBot", role: "AI Assistant", color: "#4ecdc4" } + ]; + + // 2. STATE: Start by showing the first user + const [currentUser, setCurrentUser] = React.useState(users[0]); + + // 3. CHILD COMPONENT: Receives info via Props + const ProfileCard = ({ name, role, color }) => ( +
+
+ {name[0]} +
+

{name}

+

{role}

+
+ ); + + return ( +
+

Select a Team Member:

+ + {/* 4. NAVIGATION: Buttons to update State */} +
+ {users.map(user => ( + + ))} +
+ + {/* 5. DISPLAY: Passing current state as props */} + +
+ ); +} + +``` + +## Level Up Challenges + +If the code above was too easy for you, try adding these features: + +1. **Status State:** Add a button inside the `ProfileCard` that toggles a "Status" between "Available" and "Busy." +2. **Add a Dynamic Message:** Add a `message` property to each user object and display it in the card. +3. **Dark Mode:** Add a global state that toggles the entire app background between light and dark. + +## What did you just prove? + +By finishing this, you have officially moved past "HTML/CSS" thinking. You are now: + +* **Managing Data:** Using arrays and state. +* **Building Components:** Making reusable UI templates. +* **Connecting Logic:** Letting user actions (clicks) drive the interface. + +:::success Graduation Day! +You have completed the **React Beginners** module at **CodeHarborHub**. You now have the foundation to explore advanced concepts like **API Fetching**, **Routing**, and **Global State Management**. + +Keep building, keep breaking things, and most importantly, keep sailing! +::: \ No newline at end of file diff --git a/absolute-beginners/frontend-beginner/react/setting-up-react.mdx b/absolute-beginners/frontend-beginner/react/setting-up-react.mdx new file mode 100644 index 0000000..31262c8 --- /dev/null +++ b/absolute-beginners/frontend-beginner/react/setting-up-react.mdx @@ -0,0 +1,99 @@ +--- +sidebar_position: 2 +title: "Setting Up Your First App" +sidebar_label: "2. Installation & Setup" +description: "See how React works in its simplest form without any complex installation." +--- + +Before we learn how to install React on your computer, let’s see what React actually *does* inside a standard webpage. + +> Most tutorials start with a "Black Box" of 1,000 files. At **CodeHarborHub**, we want you to see the "Engine" first. + +Now that you know **why** we use React, it’s time to actually build one! + +In the past, setting up React was a headache. Today, we use a tool called **Vite** (pronounced "veet," which is French for "fast"). It sets up the folders, the server, and the tools you need in about 10 seconds. + +## Step 1: The Pre-Requisites + +To run React on your computer, you must have **Node.js** installed. +* **Check it:** Open your terminal and type `node -v`. +* **Don't have it?** Download the **LTS Version** from [nodejs.org](https://nodejs.org/). + +## Step 2: Creating the Project + +Open your terminal in the folder where you want to keep your projects and run this "Magic Command": + +```bash +npm create vite@latest my-react-app -- --template react +``` + +### What happens next? + +1. **Navigate into the folder:** + + ```bash + cd my-react-app + ``` +2. **Install the "Ingredients":** + + ```bash + npm install + ``` +3. **Start the Engine:** + + ```bash + npm run dev + ``` + +**🎉 Success!** Your terminal will give you a link (usually http://localhost:5173). Open it in your browser to see your brand new React app running! + +## Step 3: Understanding the "Big Three" Files + +When you open your new project in **VS Code**, you will see many files. Don't be overwhelmed! Beginners only need to care about these three: + +1. **`index.html`**: The "Skeleton." This is the only HTML file in your project. It has one empty `
` with an ID of `root`. +2. **`main.jsx`**: The "Bridge." This file connects your React code to that `root` div in the HTML. +3. **`App.jsx`**: The "Heart." This is where you will spend 90% of your time. It is your main component. + +## The "Hello World" Test + +Let's make sure everything is working. + +1. Open `App.jsx`. +2. Delete everything inside the file. +3. Type this simple code: + +```jsx title="App.jsx" +function App() { + return ( +
+

Hello CodeHarborHub! 🚀

+

My first React app is officially alive.

+
+ ); +} + +export default App; +``` + +Check your browser at `http://localhost:5173`. If you see your message, **congratulations!** You are officially a React Developer. + + +:::warning A Note on Tools (Vite vs. CRA) +You might see older tutorials mention `create-react-app` (CRA). While it was popular for years, it is now considered outdated and slow. + +At **CodeHarborHub**, we use **Vite** because it is the professional standard for 2024 and beyond. It provides a much faster and smoother experience for developers. + +👉 **Ready to build?** For a complete, step-by-step walkthrough on installing Node.js and initializing your project, check out our [Detailed Guide to Creating Your First React App](https://codeharborhub.github.io/tutorial/react/getting-started). +::: + +## Summary Checklist + +* [x] I have **Node.js** installed on my machine. +* [x] I created a project using the **Vite** template. +* [x] I know that `App.jsx` is the main file I need to edit. +* [x] My local development server is running. + +:::tip Pro Tip +Keep your terminal open while you code! Every time you press **Save** (Ctrl+S) in VS Code, Vite will automatically refresh your browser instantly. This is called **Hot Module Replacement (HMR)**. +::: \ No newline at end of file diff --git a/absolute-beginners/frontend-beginner/react/thinking-in-components.mdx b/absolute-beginners/frontend-beginner/react/thinking-in-components.mdx new file mode 100644 index 0000000..bbca339 --- /dev/null +++ b/absolute-beginners/frontend-beginner/react/thinking-in-components.mdx @@ -0,0 +1,158 @@ +--- +sidebar_position: 3 +title: "Thinking in Components" +sidebar_label: "3. Thinking in Components" +description: "Learn how to decompose a user interface into a hierarchy of reusable components." +--- + +The secret to being a great React developer isn't knowing complex math, it's knowing how to **break things down**. + +In traditional web development, we build pages (`home.html`, `about.html`). In React, we build **UI Pieces** (Components) and snap them together. + +## The "X-Ray" Vision + +Imagine you are looking at a simple Social Media post. If we look at it with "React X-Ray Vision," we see that it's actually made of several smaller pieces: + +```mermaid +graph TD + App[App Container] --> Nav[Navbar] + App --> Feed[Post Feed] + Feed --> Post1[Post Component] + Feed --> Post2[Post Component] + Post1 --> User[User Info] + Post1 --> Image[Post Image] + Post1 --> Btns[Like/Comment Buttons] + +``` + +## What is a Component? + +A Component is a self-contained "chunk" of code that handles its own **structure** (HTML), **style** (CSS), and **logic** (JS). + +### The Anatomy of a Component + +In React, a component is just a **JavaScript Function** that returns something that looks like HTML (we call this JSX). + +For example `WelcomeMessage.js` + +```jsx live +function WelcomeMessage() { + return ( +
+

Hello, CodeHarborHub!

+

Ready to build something awesome today?

+
+ ); +} + +``` + +## Why is this a Superpower? + +### 1. Reusability (Write Once, Use Everywhere) + +Need a "Subscribe" button on the top, middle, and bottom of your page? Don't copy-paste the HTML. Just use your ` + ); +}; + +export default Button; +``` + +**Usage in an App** + +You can then import and use this component throughout your application: + +```jsx title="src/App.js" +import React, { useState } from 'react'; +import Button from './components/Button'; + +function App() { + const [count, setCount] = useState(0); + + const handleClick = () => { + setCount(count + 1); + }; + + return ( +
+

Current count: {count}

+ + + +
+ ); +} + +export default App; +``` + +**Key Features and Customization** + +* **Props:** The component accepts props like onClick, children, disabled, and type to manage its behavior and content. +* **Styling:** Styles can be applied using standard CSS, CSS modules, or libraries like styled components or Tailwind CSS. +* **Icons and Loading States:** Advanced components often include support for icons, different sizes, and a loading state (e.g., displaying a spinner while an asynchronous action is pending). +* **Third-Party Libraries:** Many UI libraries provide feature-rich, pre-styled button components out of the box, such as Material UI, React Bootstrap, and Syncfusion. + +::: + +### 2. Isolation (Don't Break the Whole House) + +If your "Search Bar" component has a bug, the "Video Player" component will still work perfectly. They are independent of each other. + +### 3. Maintenance (The "Single Source of Truth") + +If you want to change the color of every button on your site, you only have to change it in **one file**: `Button.js`. + +## Beginner Exercise: The Component Breakdown + +Look at this list. Which of these should be their own components? + +1. **A Navigation Bar?** *(Yes, it's used on every page)* +2. **A single word of text?** *(No, that's too small!)* +3. **A Product Card?** *(Yes, you'll have many of them on a shop page)* +4. **An Input Field with a Label?** *(Yes, it's a reusable form element)* + +:::tip The Component Rule of Thumb + +If a piece of your UI is **repeated** (like a card) or is **complex** (like a video player), it should be a **Component**. + +::: + +## Summary Checklist + +* [x] I can visualize a website as a "Tree" of components. +* [x] I understand that components are just JS functions. +* [x] I know that "Nesting" means putting one component inside another. + +:::info Did you know? +In a massive app like **Facebook**, there are over **50,000 components**! Because they are so well-organized, thousands of developers can work on them at the same time without stepping on each other's toes. +::: \ No newline at end of file