Skip to content

You are viewing a free preview of this lesson.

Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.

React Fundamentals

React Fundamentals

React is a JavaScript library for building user interfaces. It lets you compose complex UIs from small, isolated pieces of code called components. This lesson covers the building blocks — JSX, components, props, lists, conditional rendering, and how to think in React.


What Is React?

React was created by Facebook (now Meta) and released in 2013. It popularised the idea of declarative, component-based UI development:

Concept Description
Declarative You describe what the UI should look like, not how to update it
Component-based UIs are built from reusable, self-contained pieces
Unidirectional data flow Data flows down from parent to child via props

JSX — JavaScript XML

JSX is a syntax extension that lets you write HTML-like markup inside JavaScript:

// JSX looks like HTML but lives inside JavaScript
const heading = <h1>Hello, React!</h1>;

JSX Rules

  1. Return a single root element — wrap siblings in a <div> or a <Fragment> (<>...</>)
  2. Close all tags — self-closing tags like <img /> and <br /> need the slash
  3. Use className instead of class — because class is a reserved word in JavaScript
  4. Use curly braces {} for JavaScript expressions
const name = "Alice";
const element = (
  <div className="greeting">
    <h1>Hello, {name}!</h1>
    <p>2 + 2 = {2 + 2}</p>
  </div>
);

Components

A component is a JavaScript function that returns JSX. Component names must start with a capital letter.

Function Component

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

Arrow Function Component

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

Using a Component

function App() {
  return (
    <div>
      <Welcome />
      <Welcome />
    </div>
  );
}

Props — Passing Data to Components

Props (short for "properties") let you pass data from a parent component to a child component:

interface GreetingProps {
  name: string;
  age: number;
}

function Greeting({ name, age }: GreetingProps) {
  return (
    <p>
      Hello, {name}! You are {age} years old.
    </p>
  );
}

// Usage
<Greeting name="Alice" age={30} />

Props Are Read-Only

A component must never modify its own props. Props flow down — they are read-only from the child's perspective.

  ┌──────────┐
  │  Parent   │
  │           │──── name="Alice" ────▶ ┌───────────┐
  │           │                        │  Greeting  │
  │           │──── age={30} ────────▶ │           │
  └──────────┘                        └───────────┘

The children Prop

Components can accept nested JSX as children:

interface CardProps {
  title: string;
  children: React.ReactNode;
}

function Card({ title, children }: CardProps) {
  return (
    <div className="card">
      <h2>{title}</h2>
      <div className="card-body">{children}</div>
    </div>
  );
}

// Usage
<Card title="Welcome">
  <p>This is the card body content.</p>
</Card>

Rendering Lists

Use .map() to render arrays of data. Each item must have a unique key prop:

interface User {
  id: number;
  name: string;
}

const users: User[] = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 3, name: "Charlie" },
];

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

Why Keys Matter

Without keys With keys
React re-renders every item React only re-renders changed items
Poor performance on large lists Efficient, minimal DOM updates
Bugs with component state State correctly tracks each item

Tip: Never use array indices as keys if items can be reordered, added, or removed. Use a stable unique identifier like id.


Conditional Rendering

Using Ternary Operator

function Status({ isLoggedIn }: { isLoggedIn: boolean }) {
  return (
    <div>
      {isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
    </div>
  );
}

Using Logical AND (&&)

function Notification({ count }: { count: number }) {
  return (
    <div>
      {count > 0 && <span className="badge">{count} new messages</span>}
    </div>
  );
}

Early Return Pattern

function Dashboard({ user }: { user: User | null }) {
  if (!user) {
    return <p>Loading...</p>;
  }

  return <h1>Welcome, {user.name}!</h1>;
}

Component Composition

Building UIs by nesting components inside one another:

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

function Sidebar() {
  return (
    <aside>
      <nav>
        <ul>
          <li>Home</li>
          <li>About</li>
          <li>Contact</li>
        </ul>
      </nav>
    </aside>
  );
}

function MainContent() {
  return <main><p>Welcome to the app!</p></main>;
}

function App() {
  return (
    <div className="app-layout">
      <Header />
      <div className="content">
        <Sidebar />
        <MainContent />
      </div>
    </div>
  );
}

Component Tree

        App
       / | \
  Header  |  (content div)
        Sidebar  MainContent

Thinking in React

React encourages a specific mental model for building UIs:

  1. Break the UI into a component hierarchy — identify every component and subcomponent
  2. Build a static version first — render the UI from data using props, no state yet
  3. Identify the minimal state — what is the minimum set of data that changes?
  4. Decide where state should live — find the common ancestor component
  5. Add inverse data flow — pass callbacks down so child components can update state

Example: Product Filter

FilterableProductTable
├── SearchBar             (user types search text)
└── ProductTable
    ├── ProductCategoryRow (header for each category)
    └── ProductRow         (one row per product)

Summary

  • React is a declarative, component-based library for building UIs.
  • JSX lets you write HTML-like syntax in JavaScript, using {} for dynamic expressions.
  • Components are functions that return JSX — they are the building blocks of React apps.
  • Props pass data from parent to child and are read-only.
  • Use .map() with a unique key to render lists.
  • Conditional rendering uses ternary operators, &&, or early returns.
  • Component composition builds complex UIs from simple, reusable pieces.
  • Thinking in React is a step-by-step process: break down the UI, build static, then add state.