JSX Intro, Expressions, Attributes & If Statements
JSX lets you write HTML-like syntax inside JavaScript. Babel (or Vite) compiles JSX into React.createElement calls.
JSX Intro — JavaScript + XML
JSX lets you write HTML-like syntax inside JavaScript. Babel (or Vite) compiles JSX into React.createElement calls.
JSX is not HTML — it has small differences you must remember.
Real-life example: JSX is like writing a play script that looks like a conversation. The theater (React) turns the script into real actors on stage (DOM elements).
const element = <h1>Hello, React!</h1>;
function Welcome() {
return (
<div>
<h1>Rishtaara React Course</h1>
<p>Learn step by step.</p>
</div>
);
}JSX Expressions — { } curly braces
Put any valid JavaScript expression inside { }. Variables, math, function calls, and ternary operators all work.
Real-life example: Curly braces are like blanks in a Mad Libs story — you fill in dynamic words (JavaScript values) inside a fixed sentence (JSX).
const name = "Asha";
const score = 92;
function Report() {
return (
<div>
<p>Student: {name}</p>
<p>Double score: {score * 2}</p>
<p>Status: {score >= 40 ? "Pass" : "Fail"}</p>
</div>
);
}JSX Attributes — className, htmlFor, camelCase
Use className instead of class. Use htmlFor instead of for. Event names are camelCase: onClick, onChange, onSubmit.
Self-closing tags need a slash: <img />, <input />, <br />.
Real-life example: JSX attributes speak JavaScript dialect — same ideas as HTML, slightly different spelling so JS does not get confused with keywords.
<label htmlFor="email">Email</label>
<input id="email" className="input-field" type="email" />
<img src="/logo.png" alt="Rishtaara logo" />
<button onClick={() => console.log("clicked")}>Click</button>If Statements in JSX
You cannot write if/else directly inside JSX return. Use a ternary (? :), logical &&, or compute the value before return.
Real-life example: JSX return is one sentence on stage. You pick the right word (ternary or &&) before speaking — you do not pause mid-sentence for a full if-block.
function Greeting({ isLoggedIn, name }) {
return (
<div>
{isLoggedIn ? <p>Welcome back, {name}!</p> : <p>Please log in.</p>}
{name === "Admin" && <span className="badge">Admin</span>}
</div>
);
}
// Or compute before return
function Status({ score }) {
let message;
if (score >= 40) {
message = "Pass";
} else {
message = "Fail";
}
return <p>{message}</p>;
}