Module 11: Introduction to JSX & React

📌 What is JSX?

🔍 JSX Rules & Best Practices

🔍 JSX Examples

// Basic JSX
const name = "React";
const element = <h1>Hello, {name}!</h1>;

// JSX with attributes
const element = <img src="logo.png" alt="Logo" />;

// JSX with multiple elements (must be wrapped)
const element = (
  <div>
    <h1>Title</h1>
    <p>Paragraph</p>
  </div>
);

// Using React Fragment (no extra div)
const element = (
  <>
    <h1>Title</h1>
    <p>Paragraph</p>
  </>
);

🔍 Example: JSX vs. Regular JS

JSX:

const element = <h1>Hello, world!</h1>;

Compiled JS:

const element = React.createElement('h1', null, 'Hello, world!');

⚛️ React Basics

🔍 Basic Component Example

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

⚛️ React Components Deep Dive

🔍 Functional Components

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

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

// Using destructuring for cleaner code
function Greeting({ name, age }) {
  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>You are {age} years old.</p>
    </div>
  );
}

🔍 Component Composition

// Parent component
function App() {
  return (
    <div>
      <Header title="My App" />
      <MainContent />
      <Footer />
    </div>
  );
}

// Child components
function Header({ title }) {
  return <header><h1>{title}</h1></header>;
}

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

function Footer() {
  return <footer><p>© 2024 My App</p></footer>;
}

🔄 React State Management

🔍 useState Hook

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
      <button onClick={() => setCount(count - 1)}>
        Decrement
      </button>
    </div>
  );
}

🔍 Multiple State Variables

function UserProfile() {
  const [name, setName] = useState('');
  const [age, setAge] = useState(0);
  const [isActive, setIsActive] = useState(false);
  
  return (
    <div>
      <input 
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter name"
      />
      <input 
        type="number"
        value={age}
        onChange={(e) => setAge(Number(e.target.value))}
        placeholder="Enter age"
      />
      <label>
        <input 
          type="checkbox"
          checked={isActive}
          onChange={(e) => setIsActive(e.target.checked)}
        />
        Active
      </label>
      <p>Name: {name}, Age: {age}, Active: {isActive ? 'Yes' : 'No'}</p>
    </div>
  );
}

🔍 State Updates

🔍 Object State Example

function UserForm() {
  const [user, setUser] = useState({
    name: '',
    email: '',
    age: 0
  });
  
  const updateUser = (field, value) => {
    setUser(prevUser => ({
      ...prevUser,
      [field]: value
    }));
  };
  
  return (
    <div>
      <input 
        value={user.name}
        onChange={(e) => updateUser('name', e.target.value)}
        placeholder="Name"
      />
      <input 
        value={user.email}
        onChange={(e) => updateUser('email', e.target.value)}
        placeholder="Email"
      />
      <input 
        type="number"
        value={user.age}
        onChange={(e) => updateUser('age', Number(e.target.value))}
        placeholder="Age"
      />
      <pre>{JSON.stringify(user, null, 2)}</pre>
    </div>
  );
}

🎨 Conditional Rendering

function ConditionalComponent({ isLoggedIn, user }) {
  return (
    <div>
      {isLoggedIn ? (
        <h1>Welcome back, {user.name}!</h1>
      ) : (
        <h1>Please log in</h1>
      )}
      
      {isLoggedIn && <p>You have access to premium content.</p>}
      
      {!isLoggedIn && <button>Login</button>}
    </div>
  );
}

📋 Lists & Keys

function TodoList() {
  const [todos, setTodos] = useState([
    { id: 1, text: 'Learn React', completed: false },
    { id: 2, text: 'Build an app', completed: false },
    { id: 3, text: 'Deploy to production', completed: false }
  ]);
  
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>
          {todo.text} - {todo.completed ? 'Done' : 'Pending'}
        </li>
      ))}
    </ul>
  );
}

🎯 Event Handling

function EventExample() {
  const [message, setMessage] = useState('');
  
  const handleClick = () => {
    setMessage('Button clicked!');
  };
  
  const handleInputChange = (e) => {
    setMessage(e.target.value);
  };
  
  const handleSubmit = (e) => {
    e.preventDefault();
    alert('Form submitted: ' + message);
  };
  
  return (
    <div>
      <button onClick={handleClick}>Click me</button>
      <input onChange={handleInputChange} placeholder="Type something" />
      <form onSubmit={handleSubmit}>
        <input value={message} onChange={handleInputChange} />
        <button type="submit">Submit</button>
      </form>
      <p>Message: {message}</p>
    </div>
  );
}

✅ React: Pros & Cons

🚀 Advantages of React

⚠️ Challenges & Limitations

🏢 Why React is Widely Used in Industry

📊 Market Dominance

💼 Business Benefits

🔧 Technical Advantages

🎯 Industry Use Cases

📈 Career Opportunities

🚀 Vite: Fast React Development

🛠️ Creating a Vite + React App

npm create vite@latest my-react-app -- --template react
cd my-react-app
npm install
npm run dev

This spins up a local development server (usually on http://localhost:5173).

📦 Production Build

npm run build

This outputs a dist folder with static files you can deploy anywhere (e.g. Netlify, Vercel, S3).

📚 Learn More: Vite Documentation - Complete guide to Vite features and configuration.

🎯 Demo: Building a Basic Vite + React App

🚀 Step 1: Create the Project

# Create a new Vite project with React template
npm create vite@latest my-first-react-app -- --template react

# Navigate to the project directory
cd my-first-react-app

# Install dependencies
npm install

🔍 Step 2: Explore the Project Structure

my-first-react-app/
├── public/
│   └── vite.svg
├── src/
│   ├── assets/
│   │   └── react.svg
│   ├── App.jsx
│   ├── App.css
│   ├── index.css
│   └── main.jsx
├── index.html
├── package.json
├── vite.config.js
└── README.md

⚙️ Step 3: Start the Development Server

npm run dev

This will start the development server, usually at http://localhost:5173

🔧 Step 4: Modify App.jsx

Let's create a simple counter component:

import { useState } from 'react'
import './App.css'

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

  return (
    <div className="App">
      <header className="App-header">
        <h1>My First React App</h1>
        <div className="counter">
          <p>Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>
            Increment
          </button>
          <button onClick={() => setCount(count - 1)}>
            Decrement
          </button>
          <button onClick={() => setCount(0)}>
            Reset
          </button>
        </div>
      </header>
    </div>
  )
}

export default App

🎨 Step 5: Add Some Styling

Update App.css for better styling:

.App {
  text-align: center;
  padding: 2rem;
}

.App-header {
  background-color: #282c34;
  padding: 2rem;
  border-radius: 10px;
  color: white;
  margin: 2rem auto;
  max-width: 500px;
}

.counter {
  margin-top: 2rem;
}

.counter p {
  font-size: 1.5rem;
  margin-bottom: 1rem;
}

.counter button {
  background-color: #61dafb;
  border: none;
  padding: 0.5rem 1rem;
  margin: 0.25rem;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
}

.counter button:hover {
  background-color: #4fa8c7;}

📦 Step 6: Build for Production

npm run build

This creates a dist folder with optimized files ready for deployment.

🔍 What We Learned

🚀 Next Steps for the Demo

💡 Recap

✅ Next Steps

Happy coding!