React Fundamentals — Components, Props and JSX

Think in components, write JSX, pass props, render lists with keys, and compose a page from small pieces.

Est. 40 min Updated Suggest a fix
// Part 01 — Mental model

Describe the UI, Do Not Manually Rebuild It

React is a JavaScript library for describing user interfaces. You write a function that receives data and returns a tree of elements; React compares that description with the previous one and updates the browser DOM where needed. Instead of asking the browser to find an element and change its text after every event, you express what the screen should look like for the current data.

We will build a small study planner for Indian students preparing for semester exams or competitive tests. A learner sees a greeting, a list of study tasks, and a progress summary. The data changes over time, but the page is assembled from reusable pieces: a page shell, a task row, and a progress card.

IdeaMeaningStudy-planner example
ComponentA reusable function that returns UIStudyTask renders one task row
PropsRead-only input passed by a parentA task title and due date
JSXJavaScript syntax for describing elementsA heading plus a list
CompositionBuilding a larger UI from smaller componentsPlannerPage uses ProgressCard and StudyTask
💡 Note
A component should be a useful unit of UI, not automatically one component per HTML tag. Start with a clear responsibility and split when reuse or readability improves.
// Part 02 — JSX

JSX Is a JavaScript Expression

JSX resembles HTML but is compiled into JavaScript calls. It lets markup and logic live near one another while still following JavaScript rules. Use className for CSS classes, close every tag, and wrap sibling elements in one parent or a fragment. Insert an expression with braces; an expression produces a value, while a statement such as an if block does not fit directly inside JSX.

StudyHeader.tsx
tsx
type StudyHeaderProps = { studentName: string; exam: string }

export function StudyHeader({ studentName, exam }: StudyHeaderProps) {
  const firstName = studentName.trim().split(" ")[0] || "Learner"
  return (
    <header className="page-header">
      <p>Good evening, {firstName}</p>
      <h1>{exam} study plan</h1>
      <p>Small, consistent sessions add up.</p>
    </header>
  )
}

Braces let you insert a variable or an expression, such as a function call or conditional expression. Keep computation readable: derive a short display value before the return rather than nesting several operations into an unreadable line.

// Part 03 — Components

Make Components Small and Composable

A component is a normal JavaScript function whose name begins with a capital letter and whose result is renderable UI. Capitalization tells JSX that StudyHeader is a component, while header is a browser element. Put reusable components in separate files when the project grows; for an early exercise, a few components in one file makes the composition visible.

StudyPlanner.tsx
tsx
type Task = { id: string; title: string; subject: string; minutes: number }

type TaskRowProps = { task: Task }

function TaskRow({ task }: TaskRowProps) {
  return (
    <li className="task-row">
      <div><strong>{task.title}</strong><span>{task.subject}</span></div>
      <span>{task.minutes} min</span>
    </li>
  )
}

function TaskList({ tasks }: { tasks: Task[] }) {
  if (tasks.length === 0) return <p>No sessions yet. Add one to get started.</p>
  return <ul>{tasks.map((task) => <TaskRow key={task.id} task={task} />)}</ul>
}

export function StudyPlanner() {
  const tasks: Task[] = [
    { id: "math-1", title: "Revise matrices", subject: "Mathematics", minutes: 45 },
    { id: "cs-1", title: "Practise SQL joins", subject: "Computer science", minutes: 30 },
  ]
  return <main><h1>This week</h1><TaskList tasks={tasks} /></main>
}

The list component owns the list presentation, while each row owns one task presentation. This is composition: the parent passes the data down and the child decides how to render its part. A child should not reach into a parent component's local variables or mutate the parent's data.

🎯 Pro Tip
If a component is hard to name, mixes unrelated concerns, or is repeated in several places, that is a useful signal to reconsider its boundaries.
// Part 04 — Props

Pass Explicit Inputs Through Props

Props are the interface between a parent and a child. They make dependencies visible and allow the same component to work for many values. With TypeScript, define the expected shape so a missing title or a misspelled field becomes an editor or compiler warning rather than a subtle visual bug.

ProgressCard.tsx
tsx
type ProgressCardProps = {
  completedSessions: number
  plannedSessions: number
  studentName: string
}

export function ProgressCard({
  completedSessions, plannedSessions, studentName,
}: ProgressCardProps) {
  const percent = plannedSessions === 0
    ? 0
    : Math.round((completedSessions / plannedSessions) * 100)

  return (
    <section aria-label="Weekly progress">
      <h2>{studentName}'s progress</h2>
      <p>{completedSessions} of {plannedSessions} sessions complete</p>
      <progress value={percent} max={100}>{percent}%</progress>
    </section>
  )
}

Notice that progress is derived from the two input numbers. Do not store both the source values and a percentage that can be calculated from them; duplicate state can drift out of sync. Props are read-only by convention: if a child needs a change, it asks the parent through a callback, which we will use in the next lesson.

// Part 05 — Lists

Render Data Collections with Stable Keys

Use JavaScript's map to transform an array into elements. React needs a stable key on each repeated item so it can match the same task between renders. A database identifier or a persistent ID is best. Array indexes are unsafe when items can be reordered, inserted, or deleted because React may associate a row's old state with a different task.

TaskList.tsx
tsx
type Task = { id: string; title: string; subject: string }

export function TaskList({ tasks }: { tasks: Task[] }) {
  if (tasks.length === 0) {
    return <p>Your plan is empty. Add a short study session.</p>
  }

  return (
    <ul>
      {tasks.map((task) => (
        <li key={task.id}>
          <strong>{task.title}</strong>
          <span> — {task.subject}</span>
        </li>
      ))}
    </ul>
  )
}

Keys are special instructions for React and are not passed as ordinary props. If the row needs the ID for a button handler, pass taskId={task.id} separately. Always plan for the empty state: a blank area does not tell a student whether the app is loading, broken, or simply has no sessions.

📌 Real World Example
For a student in Hyderabad with no plan created yet, show a clear empty-state message and an action to add the first session; do not show a fabricated sample task as if it were saved data.
// Part 06 — Project structure

Compose the First Planner Screen

Start with static, believable data and focus on the component tree. Once it is readable, you can add interactions and connect it to a server. Keep one source of truth for each piece of data, give components semantic HTML, and use actual headings, lists, and buttons so keyboard and assistive-technology users can understand the page.

  1. Create a page shell that owns the student name and the current week title.
  2. Create a ProgressCard with counts passed as props.
  3. Create a TaskList that handles both populated and empty arrays.
  4. Create a TaskRow that presents one task without knowing where it came from.
  5. Render the page and check the browser console for missing-key warnings.

Components should be deterministic for the same props. Avoid reading from the browser, fetching data, or changing global variables during render. Those concerns belong in effects, event handlers, or server-side data access, which later lessons introduce.

// Part 07 — Pitfalls

Common Mistakes

Using a lowercase component name

Why: JSX treats lowercase names as native HTML elements.

Fix: Use PascalCase, such as StudyTask, for your own components.

Using array position as a key for editable rows

Why: Reordering changes which record an index refers to.

Fix: Use a stable ID from the task or create one when the task is created.

Mutating a prop or shared array

Why: React cannot reliably detect the intended change and other consumers see surprises.

Fix: Treat props as immutable and send changes to the owner through callbacks.

Returning several adjacent JSX roots

Why: A component must return one tree root.

Fix: Wrap siblings in a semantic element or a fragment.

// Part 08 — Practice

Build a Read-Only Study Plan

Practice

A planner screen that is ready to become interactive

  1. Create a StudyHeader that accepts a student name and exam name as typed props.
  2. Define a Task type and render three study sessions with stable IDs and keys.
  3. Create a reusable ProgressCard and derive its percentage from completed and planned counts.
  4. Show a helpful empty state when the task array is empty.
  5. Inspect the screen at a narrow viewport and make long subject names wrap without breaking the layout.

Hint: Keep this version static. The next lesson adds controlled form state and completion actions.

🎯 Key Takeaways

  • ✓A React component describes UI as a function of its inputs.
  • ✓JSX is JavaScript syntax with rules: one root, closed tags, className, and braces for expressions.
  • ✓Props define explicit, read-only inputs and can be typed with TypeScript.
  • ✓Compose a page from components with clear responsibilities.
  • ✓Map arrays to elements with stable keys and deliberate empty states.
  • ✓Derive display values instead of storing duplicate data that can become inconsistent.
  • Prerequisite: JavaScript & TypeScript. Consult the official React documentation for JSX, components, and rendering lists.

Next

What comes next

Give the planner controlled forms, completion buttons, and reliable loading states with React state and effects.

Lesson 02 · React State, Effects and Data Fetching →

HELP US IMPROVE

How was this lesson?

Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.

Choose your feedback

Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.

Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...