MODULE 4

React Fundamentals

Master the core concepts every React developer needs to know

JSX: JavaScript XML

JSX allows you to write HTML-like code in JavaScript. It's the syntax that makes React so readable.

What is JSX?

// JSX
const element = 

Hello, World!

; // What it becomes (JavaScript) const element = React.createElement('h1', null, 'Hello, World!');

JSX looks like HTML but it's actually JavaScript. The browser doesn't understand JSX directly—it gets compiled to JavaScript function calls.

JSX Rules

  1. One root element: Wrap multiple elements in a fragment or div
  2. Close all tags: Even self-closing tags like
  3. className instead of class: Because class is a reserved keyword
  4. Use camelCase for attributes: onClick, onChange, not onclick

JSX Examples

// ✅ Valid JSX
const greeting = 

Hello

; const card = (

Title

Description

); const image = Photo; const button = ( );
// ❌ Invalid JSX
const invalid = 

Hello

World

; // Two root elements const image = ; // Not self-closed

Embedding Expressions in JSX

Use curly braces {} to embed JavaScript expressions:

const name = "Alice";
const age = 25;

const greeting = 

Hello, {name}! You are {age} years old.

; const calculation =

2 + 2 = {2 + 2}

; const conditional =

{name.length > 5 ? "Long name" : "Short name"}

;

Functional Components

Components are JavaScript functions that return JSX.

Simple Function Component

function Greeting() {
  return 

Hello, React!

; } // Or with arrow function const Greeting = () => { return

Hello, React!

; };

Component with Parameters

Components receive data through props (properties):

function Welcome(props) {
  return 

Hello, {props.name}!

; } // Usage

Destructuring Props

Extract props directly in function parameters:

function Welcome({ name, age }) {
  return (
    

Hello, {name}!

You are {age} years old.

); } // Usage

Props (Properties)

Props are how parent components pass data to child components. They're read-only.

Passing Props

function App() {
  return (
    
); } function User({ name, role }) { return

{name} is a {role}

; }

Props with Objects

function Profile({ user }) {
  return (
    

{user.name}

Email: {user.email}

City: {user.city}

); } const user = { name: "Alice", email: "alice@example.com", city: "NYC" };

Props with Children

Components can contain child elements passed as a special prop:

function Card({ children, title }) {
  return (
    

{title}

{children}
); } // Usage

This is the card content

Rendering & Re-rendering

Initial Render

When a component first appears on the page:

// This component renders once when the app starts
function App() {
  return 

Hello!

; }

Re-rendering

A component re-renders when:

  1. Its props change
  2. Its state changes (we'll learn about this in Module 5)
  3. Its parent component re-renders

Re-rendering Example

function Parent() { return (
); } function Child({ message }) { console.log("Child rendered!"); return

{message}

; } // When Parent renders, Child also renders // When message prop changes, Child re-renders

Component Composition

Build complex UIs by combining simple components:

Example: Building a Blog Post

function BlogPost({ title, author, date, content }) {
  return (
    
); } function Header({ title, author, date }) { return (

{title}

By {author} on {date}

); } function Content({ text }) { return

{text}

; } function Footer({ author }) { return

Written by {author}

; }

Fragments

Return multiple elements without a wrapper div:

Problem: Extra Div

// This adds an unnecessary div
function List() {
  return (
    

Items

  • Item 1
); }

Solution: Fragment

// No extra wrapper
function List() {
  return (
    <>
      

Items

  • Item 1
); } // Or explicitly import { Fragment } from 'react'; function List() { return (

Items

  • Item 1
); }

Conditional Rendering

if/else (Outside JSX)

function LoginButton({ isLoggedIn }) {
  if (isLoggedIn) {
    return ;
  } else {
    return ;
  }
}

Ternary Operator

Use inside JSX for simple conditions:

function UserGreeting({ isLoggedIn, name }) {
  return (
    
{isLoggedIn ? (

Welcome back, {name}!

) : (

Please log in.

)}
); }

Logical AND (&&)

Render only if condition is true:

function UserGreeting({ isLoggedIn, name }) {
  return (
    
{isLoggedIn &&

Welcome, {name}!

}
); }

Prevent Rendering with null

function Warning({ shouldShow }) {
  if (!shouldShow) {
    return null;  // Don't render anything
  }
  return 

This is a warning!

; }

Lists & Keys

Rendering Lists

Use map() to transform array data into components:

function UserList() {
  const users = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
    { id: 3, name: "Charlie" }
  ];

  return (
    
    {users.map(user => (
  • {user.name}
  • ))}
); }

Why Keys Matter

Keys help React identify which items have changed. Always use unique keys:

// ❌ Bad: Using index as key
{items.map((item, index) => )}

// ✅ Good: Using unique ID
{items.map(item => )}
⚠️ Important: Using array index as a key causes issues when the list changes. Always use a unique identifier.

Rendering Nested Data

function PostList() {
  const posts = [
    {
      id: 1,
      title: "First Post",
      comments: [
        { id: 1, text: "Great!" },
        { id: 2, text: "Thanks!" }
      ]
    },
    {
      id: 2,
      title: "Second Post",
      comments: [
        { id: 3, text: "Nice post" }
      ]
    }
  ];

  return (
    
{posts.map(post => (

{post.title}

    {post.comments.map(comment => (
  • {comment.text}
  • ))}
))}
); }

Common Patterns

Conditional Component

function Status({ status }) {
  switch(status) {
    case "loading":
      return 

Loading...

; case "success": return

Success!

; case "error": return

Error occurred

; default: return

Unknown status

; } }

Default Props

function Button({ label = "Click me", disabled = false }) {
  return ;
}

// Usage

Key Takeaways

Component structure

Practice Exercise

  1. Create a Card component that accepts title and description props
  2. Create a list of cards using an array of data
  3. Add conditional rendering to show/hide content
  4. Use fragments to return multiple elements