Skip to main content

03. JSX and React Components

Level: Beginner

ℹ️ What You'll Learn
  • JSX syntax and how React interprets it
  • Creating functional components
  • Props: passing data to components
  • Component composition and reusability
  • Build reusable SMS StudentCard component
  • Best practices for component structure

The Problem

JavaScript fundamentals aren't enough. React components are a different way of thinking. JSX looks like HTML but it's JavaScript. Components take props. Components must return JSX. If you write components wrong, you'll face prop bugs, re-render issues, and confusion about when code runs.

You've learned JavaScript fundamentals. Now build your first React component.

What is JSX?

JSX looks like HTML inside JavaScript:

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

But it's not a string. React converts it to function calls:

// JSX
<h1>Hello, Ravi!</h1>

// What React actually does
React.createElement('h1', null, 'Hello, Ravi!')

JSX combines HTML-like syntax with JavaScript logic. That's the magic.

JSX Rules

1. Only One Root Element

// ❌ Wrong — two root elements
return (
<h1>Student</h1>
<p>Ravi Kumar</p>
);

// ✓ Correct — wrap in one element
return (
<div>
<h1>Student</h1>
<p>Ravi Kumar</p>
</div>
);

// ✓ Also correct — fragment (invisible wrapper)
return (
<>
<h1>Student</h1>
<p>Ravi Kumar</p>
</>
);

2. Embed JavaScript with

const name = "Ravi Kumar";
const marks = 95;
const className = "10";

// Embed variables
const element = (
<div>
<h1>{name}</h1>
<p>Marks: {marks}</p>
<p>Class: {className}</p>
</div>
);

// Embed expressions
<div>
<p>Average marks: {marks / 2}</p>
<p>Passed: {marks >= 40 ? "Yes" : "No"}</p>
<p>{marks > 90 ? "Excellent" : marks > 80 ? "Good" : "Pass"}</p>
</div>

// Embed function calls
<div>
<p>Total: {calculateTotal(exam1, exam2)}</p>
</div>

3. className Instead of class

HTML uses class. JSX uses className (because class is reserved in JavaScript).

// ❌ Wrong
<div class="student-card">Ravi</div>

// ✓ Correct
<div className="student-card">Ravi</div>

4. Attributes Use camelCase

// ❌ Wrong
<input onclick={handleClick} />

// ✓ Correct
<input onClick={handleClick} />

// Event handlers are camelCase
onSubmit, onChange, onFocus, onBlur, onMouseEnter, etc.

5. Self-Closing Tags

// These must self-close in JSX
<img src="logo.png" />
<input type="text" />
<hr />
<br />

6. Comments Inside JSX

return (
<div>
{/* This is a comment */}
<h1>Student</h1>
{/* Render marks if available */}
{marks && <p>Marks: {marks}</p>}
</div>
);

Components — Your First Building Blocks

A component is a function that returns JSX.

Simple Component

function StudentCard() {
return (
<div className="card">
<h3>Ravi Kumar</h3>
<p>Class: 10</p>
<p>Roll: NCA-2024-001</p>
</div>
);
}

Use it like HTML:

// In another component
<StudentCard />

Component with Props

Props are how you pass data to components. They're like function parameters.

// Define component with props
function StudentCard({ name, className, rollNumber }) {
return (
<div className="card">
<h3>{name}</h3>
<p>Class: {className}</p>
<p>Roll: {rollNumber}</p>
</div>
);
}

// Use the component, pass props
<StudentCard name="Ravi Kumar" className="10" rollNumber="NCA-2024-001" />
<StudentCard name="Priya Sharma" className="10" rollNumber="NCA-2024-002" />
<StudentCard name="Arjun Reddy" className="11" rollNumber="NCA-2024-101" />

Building Components for School Management System

Example 1: Teacher Card

function TeacherCard({ teacher }) {
return (
<div className="teacher-card">
<h3>{teacher.name}</h3>
<p>Subject: {teacher.subject}</p>
<p>Experience: {teacher.experienceYears} years</p>
<p>Qualification: {teacher.qualification}</p>
</div>
);
}

// Usage
const teacher = {
name: "Dr. Mehta",
subject: "Mathematics",
experienceYears: 15,
qualification: "M.Sc, B.Ed"
};

<TeacherCard teacher={teacher} />

Example 2: Exam Result Card

function ExamResultCard({ exam, marks, status }) {
const isPassed = marks >= exam.passingMarks;

return (
<div className="result-card">
<h4>{exam.name}</h4>
<p>Marks: {marks} / {exam.maxMarks}</p>
<p>Passing: {exam.passingMarks}</p>
<p>
Status:
<span className={isPassed ? "passed" : "failed"}>
{isPassed ? "Passed" : "Failed"}
</span>
</p>
</div>
);
}

// Usage
<ExamResultCard
exam={{ name: "Maths Unit Test", maxMarks: 50, passingMarks: 20 }}
marks={45}
status="Passed"
/>

Example 3: Fee Status Badge

function FeeStatusBadge({ status, dueAmount }) {
const statusColor = {
'Paid': 'green',
'Pending': 'red',
'Partial': 'orange',
'Overdue': 'darkred'
};

return (
<div className={`badge badge-${statusColor[status]}`}>
<p>{status}</p>
{dueAmount > 0 && <p>Due: ₹{dueAmount}</p>}
</div>
);
}

// Usage
<FeeStatusBadge status="Partial" dueAmount={5000} />
<FeeStatusBadge status="Paid" dueAmount={0} />

Component Rules

1. Component Names Start with Capital Letter

// ❌ Wrong — component won't render
function studentCard() { }

// ✓ Correct — capital letter
function StudentCard() { }

// Or arrow function
const StudentCard = () => { };

2. Components Must Return Something

// ❌ Wrong — returns nothing
function StudentCard() {
console.log("Rendering...");
}

// ✓ Correct — returns JSX
function StudentCard() {
return <div>Student</div>;
}

3. Props Are Read-Only

Don't modify props. Props are like function parameters — they flow one way.

// ❌ Wrong — modifying props
function StudentCard({ student }) {
student.name = "Changed"; // ❌ Don't do this
return <h1>{student.name}</h1>;
}

// ✓ Correct — just use props
function StudentCard({ student }) {
return <h1>{student.name}</h1>;
}

Nesting Components

Components can contain other components.

function StudentProfile({ student }) {
return (
<div className="profile">
<StudentCard student={student} />
<StudentDetails student={student} />
<StudentMarks studentId={student.id} />
</div>
);
}

function StudentCard({ student }) {
return <h2>{student.name}</h2>;
}

function StudentDetails({ student }) {
return (
<div>
<p>Class: {student.className}</p>
<p>Roll: {student.rollNumber}</p>
</div>
);
}

function StudentMarks({ studentId }) {
return <p>Marks loading...</p>;
}

// Usage
<StudentProfile student={raviStudent} />

Props Best Practices

1. Destructure Props

// ❌ Less clear
function StudentCard(props) {
return <h1>{props.name}</h1>;
}

// ✓ Clearer
function StudentCard({ name, className }) {
return <h1>{name} - {className}</h1>;
}

2. Use Meaningful Prop Names

// ❌ Unclear
<StudentCard data={student} fn={handleDelete} />

// ✓ Clear
<StudentCard student={student} onDelete={handleDelete} />

3. Default Props

function StudentBadge({ student, size = "medium" }) {
return <div className={`badge-${size}`}>{student.name}</div>;
}

<StudentBadge student={ravi} /> // Uses size="medium"
<StudentBadge student={priya} size="large" /> // Uses size="large"

Converting HTML to JSX

If you have HTML, converting to JSX is simple:

<!-- HTML -->
<div class="student-card">
<h3>Ravi Kumar</h3>
<p>Class: 10</p>
<img src="ravi.jpg" alt="Student" />
</div>
// JSX (same structure, small changes)
<div className="student-card">
<h3>Ravi Kumar</h3>
<p>Class: 10</p>
<img src="ravi.jpg" alt="Student" />
</div>

// As a component
function StudentCard() {
return (
<div className="student-card">
<h3>Ravi Kumar</h3>
<p>Class: 10</p>
<img src="ravi.jpg" alt="Student" />
</div>
);
}

Summary

  • JSX looks like HTML but it's JavaScript
  • Components are functions that return JSX
  • Props pass data into components
  • Use {} to embed JavaScript
  • Components are reusable building blocks

Start thinking of your UI as components. "What's reusable? What's repeated?" Those are components.

⚠️ Common Mistakes
  1. Forgetting className — Use className, not class
  2. Using lowercase component namesstudentCard won't work, use StudentCard
  3. Modifying props directly — Props are read-only
  4. Forgetting curly braces<div>{variable}</div>, not <div>variable</div>
  5. Multiple root elements — Wrap in <div> or <>
💡 Keep Components Small

Each component should do one thing well. If a component is getting big, break it into smaller pieces.

Instead of:

function StudentDashboard() {
return (
// 300 lines of code
);
}

Break it into:

function StudentDashboard() {
return (
<>
<StudentProfile />
<StudentMarks />
<StudentAttendance />
</>
);
}
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on Components and JSX. Try these prompts:

  • "Convert this HTML to JSX: '<div class="card"><h1>Title</h1></div>'"
  • "Why must component names start with capital letters?"
  • "What's the difference between props and state? (we'll cover state later)"
  • "Quiz me on JSX rules and components"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Quick Definitions

  • JSX and React Components - The main React concept explained in this lesson.
  • Component - A reusable function that returns UI.
  • Props/state/effects - Core React ideas used to pass data, remember data, and run side effects.
  • Real project usage - How this appears in forms, dashboards, routes, and API-connected pages.

Common Mistakes

  • Copying React code without understanding data flow
  • Mutating arrays or objects directly instead of creating new values
  • Forgetting keys, dependencies, loading states, or error states where needed
  • Putting too much logic in one component
  • Not testing the screen with realistic School Management System data

Practice Task

Create a small React example using JSX and React Components. Keep it focused on one School Management System screen.

Suggested practice:

  1. Build a small component or page for students, attendance, marks, or fees.
  2. Pass realistic data into the component.
  3. Add one success state and one empty/error state where relevant.
  4. Explain the data flow in your own words.
  5. Rebuild the same example once without looking at the article.

Quick Revision

QuestionAnswer
What is the main idea?Understand and apply JSX and React Components in React.
Where is it used?Student dashboards, forms, tables, routes, and API-connected screens.
What should beginners focus on?Clear components, predictable data flow, and small examples.
What is the best debugging habit?Check props, state, render output, and browser console step by step.
🎯 How would you explain JSX and React Components in an interview?

JSX and React Components is a React concept used to build clear, reusable, and predictable user interfaces. I would explain the problem it solves, show a small component example, and mention a common mistake beginners should avoid.

🎯 Where is this used in a real React project?

It is used in screens like student lists, admission forms, attendance dashboards, marks reports, routing pages, and API-connected admin panels.

Next Article

Props — Passing Data to Components ->

nexcoding.in