React.js Notes

Class 01

1. Introduction to React.js

What is React?

React ek JavaScript library hai jo user interfaces (UI) banane ke liye use hoti hai. Yeh Facebook ne develop ki thi aur ab open-source hai. React ka main focus fast, scalable, aur simple web applications banane par hota hai.

Why Use React?

1. Component-Based Architecture

2. Fast Performance (Virtual DOM)

3. Single Page Application (SPA) Development

4. Reusability & Maintainability

2. Single Page Application (SPA)

What is SPA?

SPA ek aisi web application hai jo sirf ek HTML page load karti hai aur dynamically content update karti hai bina page reload kiye.

How SPA Works?

1. Initial Load

2. Routing (Client-Side Routing)

3. React vs. Vanilla JavaScript

Feature React Vanilla JavaScript
Type JavaScript Library Plain JavaScript
DOM Manipulation Uses Virtual DOM (Fast) Uses Real DOM (Slower)
UI Structure Component-Based Architecture Manually manage karna hota hai
Performance Fast due to Virtual DOM Slow due to direct DOM updates
Reusability Components can be reused Code reuse difficult

Class 02

4. JSX (JavaScript XML)

What is JSX?

JSX ek syntax extension hai jo React ke andar HTML-like structure likhne ke liye use hota hai. Yeh JavaScript ke andar HTML likhne ki suvidha deta hai.

Why Use JSX?

What is useState Hook?

useState is a React Hook that allows you to add state management to functional components. It helps store and update values within a component, ensuring React re-renders the component whenever the state changes.

Why Use useState Instead of Regular Variables?

React does not track changes in normal variables, meaning updates won’t trigger a re-render of the component. useState ensures that when a state value changes, React automatically updates the UI.

Example: Counter App

Counter with Variable (UI Doesn't Update)

                
let count = 0;

function Example() {
  function increase() {
    count += 1;
    console.log(count); // Updates in console, but UI doesn't update
  }

  return (
    <div>
      <p>Count: {count}</p> {/* UI remains the same */}
      <button onClick={increase}>Increase</button>
    </div>
  );
}
                
            

Issue Using Variable

The UI does not update when count changes because React does not track it.

Counter with useState (UI Updates Correctly)

                
import { useState } from "react";

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

  function increase() {
    setCount(count + 1); // Updates state and re-renders the component
  }

  return (
    <div>
      <p>Count: {count}</p> {/* UI updates correctly */}
      <button onClick={increase}>Increase</button>
    </div>
  );
}
                
            

Why useState is Better?

useState Real-World Use Cases

1. Form Handling (User Input Storage)

Use Case: When we need to store and update input values in a form.

2. Toggle Feature (Show/Hide Password, Theme Toggle, Sidebar Toggle)

Use Case: When we need to toggle a feature on/off, such as showing/hiding a password.

3. Counter App (Like Button, Cart Quantity, Steps Tracker)

Use Case: Tracking numbers such as likes, cart items, or steps.

useState Syntax

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

Breakdown

Examples of States

State with Number

                
const [count, setCount] = useState(0);
            

State with String

                
const [name, setName] = useState("abc");
            

State with Boolean

                
const [isLoggedIn, setIsLoggedIn] = useState(false);
            

State with Object

                
const [user, setUser] = useState({ name: "John Doe", age: 30 });
            

State with Array

                
const [items, setItems] = useState(["Apple", "Mango"]);
            

Handling Multiple useState Variables

Example: Form Handling with Multiple States

                
import { useState } from "react";

function UserForm() {
  const [name, setName] = useState("");
  const [age, setAge] = useState("");

  return (
    <div>
      <input
        type="text"
        placeholder="Enter name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <input
        type="number"
        placeholder="Enter age"
        value={age}
        onChange={(e) => setAge(e.target.value)}
      />
      <h3>Name: {name}, Age: {age}</h3>
    </div>
  );
}

export default UserForm;
                
            

Key Learning Points:

Task: Create a Form with Name, Email & Password Fields

Updating State with Previous State

useState with Previous Values (Why Use a Callback Function?)

Whenever the new state depends on the previous state, we should always use the callback function inside setState .

Why Should We Use a Callback Function?

React batches state updates, meaning multiple updates inside one function might not reflect immediately. If we directly use setState(value) , React might not update it as expected. Instead, we should use the function version:

                
setState((prevState) => newValue);
            

This ensures we get the latest previous value before updating.

Example

                
import { useState } from "react";

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

  const incrementByTwo = () => {
    setCount((prevCount) => prevCount + 2);
  };

  return (
    <div>
      <h2>Counter: {count}</h2>
      <button onClick={incrementByTwo}>Increment by 2</button>
    </div>
  );
}

export default Counter;
                
            

State with Arrays & Objects

Example with Array

                
import { useState } from "react";

function TodoList() {
  const [tasks, setTasks] = useState([]);

  const addTask = () => {
    setTasks([...tasks, `Task ${tasks.length + 1}`]);
  };

  return (
    <div>
      <button onClick={addTask}>Add Task</button>
      <ul>
        {tasks.map((task, index) => (
          <li key={index}>{task}</li>
        ))}
      </ul>
    </div>
  );
}

export default TodoList;
                
            

Task: Create a "To-Do List" Where Users Can Add and Remove Items

Example of To-Do List

                
import { useState } from "react";

function TodoList() {
  const [tasks, setTasks] = useState([]);
  const [task, setTask] = useState("");

  // Function to add a new task
  const addTask = () => {
    if (task.trim() !== "") {
      setTasks([...tasks, task]);
      setTask(""); // Clear input field
    }
  };

  // Function to remove a task
  const removeTask = (index) => {
    const updatedTasks = tasks.filter((_, i) => i !== index);
    setTasks(updatedTasks);
  };

  return (
    <div style={{ textAlign: "center", padding: "20px" }}>
      <h2>To-Do List</h2>
      <input
        type="text"
        placeholder="Enter a task"
        value={task}
        onChange={(e) => setTask(e.target.value)}
      />
      <button onClick={addTask}>Add Task</button>

      <ul>
        {tasks.map((t, index) => (
          <li key={index}>
            {t} <button onClick={() => removeTask(index)}>❌</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default TodoList;
                
            

Dark Mode & Light Mode Using useState

                
import { useState } from "react";

function ThemeSwitcher() {
  const [darkMode, setDarkMode] = useState(false);

  return (
    <div style={{ background: darkMode ? "black" : "white", color: darkMode ? "white" : "black", height: "100vh", textAlign: "center", padding: "50px" }}>
      <h1>{darkMode ? "Dark Mode" : "Light Mode"}</h1>
      <button onClick={() => setDarkMode(!darkMode)}>Toggle Theme</button>
    </div>
  );
}

export default ThemeSwitcher;
                
            

Class 03

Components and Props

1. What are Components?

Components are the building blocks of a React application. They are reusable and independent pieces of code that represent a part of the user interface (UI). Each component can have its own state, logic, and structure.

Types of Components

2. Functional Components

Functional components are the simplest way to create a component. They are JavaScript functions that return JSX.

Example of a Functional Component

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

export default Greeting;
                
            

Key Points:

3. Class Components

Class components are ES6 classes that extend React.Component . They have additional features like state and lifecycle methods.

Example of a Class Component

                
import React from "react";

class Greeting extends React.Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}

export default Greeting;
                
            

Key Points:

4. Props (Properties)

Props are used to pass data from one component to another. They are read-only and help make components reusable and dynamic.

Example of Using Props

                
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

export default Greeting;
                
            

Usage:

                
import Greeting from "./Greeting";

function App() {
  return (
    <div>
      <Greeting name="John" />
      <Greeting name="Jane" />
    </div>
  );
}

export default App;
                
            

Key Points:

5. Default Props

Default props are used to provide default values for props in case they are not passed from the parent component.

Example of Default Props

                
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

Greeting.defaultProps = {
  name: "Guest",
};

export default Greeting;
                
            

Usage:

                
import Greeting from "./Greeting";

function App() {
  return (
    <div>
      <Greeting /> {/* Output: Hello, Guest! */}
      <Greeting name="John" /> {/* Output: Hello, John! */}
    </div>
  );
}

export default App;
                
            

6. PropTypes

PropTypes are used to validate the type of props passed to a component. They help catch bugs by ensuring that the correct data types are passed.

Example of PropTypes

                
import PropTypes from "prop-types";

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

Greeting.propTypes = {
  name: PropTypes.string.isRequired,
};

export default Greeting;
                
            

Key Points:

7. Passing Functions as Props

Functions can also be passed as props to child components. This allows child components to communicate with parent components.

Example of Passing Functions as Props

                
function ChildComponent(props) {
  return <button onClick={props.onClick}>Click Me</button>;
}

function ParentComponent() {
  const handleClick = () => {
    alert("Button clicked!");
  };

  return <ChildComponent onClick={handleClick} />;
}

export default ParentComponent;
                
            

8. Component Composition

Component composition is the process of combining smaller components to build more complex UIs. It promotes reusability and separation of concerns.

Example of Component Composition

                
function Header() {
  return <h1>Header</h1>;
}

function Content() {
  return <p>This is the content.</p>;
}

function Footer() {
  return <footer>Footer</footer>;
}

function App() {
  return (
    <div>
      <Header />
      <Content />
      <Footer />
    </div>
  );
}

export default App;
                
            

9. Task: Create a User Card Component

Create a reusable UserCard component that displays user details (name, email, and profile picture) using props.

Example Solution

                
function UserCard(props) {
  return (
    <div style={{ border: "1px solid #ccc", padding: "10px", margin: "10px", borderRadius: "5px" }}>
      <img src={props.avatar} alt="User Avatar" style={{ width: "100px", borderRadius: "50%" }} />
      <h2>{props.name}</h2>
      <p>{props.email}</p>
    </div>
  );
}

export default UserCard;
                
            

Usage:

                
import UserCard from "./UserCard";

function App() {
  const user = {
    name: "John Doe",
    email: "john@example.com",
    avatar: "https://via.placeholder.com/150",
  };

  return (
    <div>
      <UserCard name={user.name} email={user.email} avatar={user.avatar} />
    </div>
  );
}

export default App;
                
            

10. Summary

Class 04: Event Handling in React

1. What is Event Handling?

Event handling in React allows you to respond to user interactions like clicks, input changes, form submissions, etc. React events are similar to DOM events but are written in camelCase (e.g., onClick instead of onclick ).

2. Common Events in React

React supports a wide range of events. Here are some commonly used ones:

Event Description
onClick Triggered when an element is clicked.
onChange Triggered when the value of an input, select, or textarea changes.
onSubmit Triggered when a form is submitted.
onMouseOver Triggered when the mouse pointer moves over an element.
onKeyDown Triggered when a key is pressed down.

3. Handling Events in React

In React, event handlers are passed as functions to the event attributes (e.g., onClick , onChange ). These functions are called when the event occurs.

Example: Handling a Click Event

                
function App() {
  const handleClick = () => {
    alert("Button clicked!");
  };

  return (
    <div>
      <button onClick={handleClick}>Click Me</button>
    </div>
  );
}

export default App;
                
            

Example: Handling an Input Change Event

                
function App() {
  const [inputValue, setInputValue] = useState("");

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

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="Type something..."
      />
      <p>You typed: {inputValue}</p>
    </div>
  );
}

export default App;
                
            

4. Passing Arguments to Event Handlers

Sometimes, you may need to pass additional arguments to an event handler. This can be done using an arrow function.

Example: Passing Arguments

                
function App() {
  const handleClick = (message) => {
    alert(message);
  };

  return (
    <div>
      <button onClick={() => handleClick("Hello!")}>Say Hello</button>
      <button onClick={() => handleClick("Goodbye!")}>Say Goodbye</button>
    </div>
  );
}

export default App;
                
            

5. Preventing Default Behavior

In some cases, you may want to prevent the default behavior of an event (e.g., preventing a form from submitting). This can be done using event.preventDefault() .

Example: Preventing Form Submission

                
function App() {
  const handleSubmit = (event) => {
    event.preventDefault();
    alert("Form submitted!");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" placeholder="Enter your name" />
      <button type="submit">Submit</button>
    </form>
  );
}

export default App;
                
            

6. Synthetic Events

React uses synthetic events to wrap native browser events. These events work consistently across all browsers and provide additional features.

Key Points:

7. Task: Create a Button That Toggles Text

Create a button that toggles between "Show" and "Hide" text when clicked.

Example Solution

                
function App() {
  const [showText, setShowText] = useState(true);

  const toggleText = () => {
    setShowText(!showText);
  };

  return (
    <div>
      <button onClick={toggleText}>{showText ? "Hide" : "Show"}</button>
      {showText && <p>This is some text!</p>}
    </div>
  );
}

export default App;
                
            

8. Task: Create a Form with Validation

Create a form with name and email fields. Validate that both fields are filled before allowing submission.

Example Solution

                
function App() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();

    if (!name || !email) {
      setError("Please fill in all fields.");
    } else {
      setError("");
      alert(`Name: ${name}, Email: ${email}`);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <button type="submit">Submit</button>
      {error && <p style={{ color: "red" }}>{error}</p>}
    </form>
  );
}

export default App;
                
            

9. Summary

10. Using the map() Function

The map() function is a powerful JavaScript method used to transform arrays. In React, it is commonly used to render dynamic lists of components.

How map() Works

Example: Rendering a List Using map()

                
function App() {
  const fruits = ["Apple", "Banana", "Mango", "Orange"];

  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}>{fruit}</li>
      ))}
    </ul>
  );
}

export default App;
                
            

11. The Concept of Unique Keys

When rendering lists in React, each element must have a unique key . Keys help React identify which items have changed, been added, or been removed.

Why Are Keys Important?

Example: Using Unique Keys

                
function App() {
  const users = [
    { id: 1, name: "John" },
    { id: 2, name: "Jane" },
    { id: 3, name: "Alice" },
  ];

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default App;
                
            

Key Points:

12. Rendering Dynamic Lists

Dynamic lists are lists where the data is not static but can change over time (e.g., fetched from an API or updated by user input). React makes it easy to render and update dynamic lists.

Example: Dynamic List with Add and Remove Functionality

                
import { useState } from "react";

function App() {
  const [tasks, setTasks] = useState([]);
  const [task, setTask] = useState("");

  const addTask = () => {
    if (task.trim() !== "") {
      setTasks([...tasks, { id: Date.now(), text: task }]);
      setTask("");
    }
  };

  const removeTask = (id) => {
    setTasks(tasks.filter((task) => task.id !== id));
  };

  return (
    <div>
      <input
        type="text"
        placeholder="Enter a task"
        value={task}
        onChange={(e) => setTask(e.target.value)}
      />
      <button onClick={addTask}>Add Task</button>

      <ul>
        {tasks.map((task) => (
          <li key={task.id}>
            {task.text} <button onClick={() => removeTask(task.id)}>❌</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;
                
            

Key Points:

13. Task: Create a Dynamic List of Users

Create a dynamic list of users where you can add and remove users. Each user should have a name and an email.

Example Solution

                
import { useState } from "react";

function App() {
  const [users, setUsers] = useState([]);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");

  const addUser = () => {
    if (name.trim() !== "" && email.trim() !== "") {
      setUsers([...users, { id: Date.now(), name, email }]);
      setName("");
      setEmail("");
    }
  };

  const removeUser = (id) => {
    setUsers(users.filter((user) => user.id !== id));
  };

  return (
    <div>
      <input
        type="text"
        placeholder="Name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <button onClick={addUser}>Add User</button>

      <ul>
        {users.map((user) => (
          <li key={user.id}>
            <strong>{user.name}</strong> - {user.email}
            <button onClick={() => removeUser(user.id)}>❌</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;
                
            

14. Summary

Class 05: React Router DOM

1. Introduction to React Router DOM

React Router DOM ek library hai jo React applications mein routing ko handle karti hai. Iska use Single Page Applications (SPAs) mein different pages ya components ko render karne ke liye kiya jata hai, bina page reload kiye.

2. Installation

React Router DOM ko use karne ke liye pehle ise install karna hoga:

npm install react-router-dom

3. Basic Setup

React Router DOM ka basic setup karna:


import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
          
function App() {
    return (
      <Router>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
      </Router>
    );
  }
            

4. Example Components

Home, About, aur Contact components ka example:

                
function Home() {
    return <h1>Home Page</h1>;
  }
  
  function About() {
    return <h1>About Us</h1>;
  }
  
  function Contact() {
    return <h1>Contact Us</h1>;
  }                    
            
        

5. Navigation with <Link>

React Router DOM mein navigation ke liye <Link> component ka use karte hain:


import { Link } from 'react-router-dom';
          
function Navbar() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
      <Link to="/contact">Contact</Link>
    </nav>
  );
}
            

6. Dynamic Routing

Dynamic routing ke liye URL parameters ka use karte hain:


<Route path="/user/:id" element={<User />} />
          
function User() {
  const { id } = useParams();
  return <h1>User ID: {id}</h1>;
}
            

7. Nested Routes

Nested routes ko define karne ke liye <Outlet> ka use karte hain:


<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>

function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>
      <Outlet />
    </div>
  );
}
            

8. 404 Page (Not Found)

Agar koi route match nahi karta hai toh 404 page dikhane ke liye:


<Route path="*" element={<NotFound />} />
          
function NotFound() {
  return <h1>404 - Page Not Found</h1>;
}
            

9. Programmatic Navigation

Programmatically navigate karne ke liye useNavigate hook ka use karte hain:


import { useNavigate } from 'react-router-dom';
          
function Login() {
  const navigate = useNavigate();
  return (
    <button onClick={() => navigate('/dashboard')}>
      Login
    </button>
  );
}
            

10. Conclusion

React Router DOM ek powerful tool hai jo SPAs mein routing ko handle karta hai. Iska use karke aap dynamic aur interactive web applications bana sakte hain.