React JSX Cheat Sheet
What is JSX?
JSX (JavaScript XML) is a syntax extension that lets you write HTML-like code inside JavaScript.
Basic Syntax
const element = <h1>Hello, world!</h1>;
Embedding Expressions
const name = "Jane";
const greeting = <p>Hello, {name}!</p>;
Using JavaScript Inside JSX
const user = { first: "Jane", last: "Doe" };
const fullName = <h2>{user.first + " " + user.last}</h2>;
Attributes in JSX
const element = <img src="logo.png" alt="Logo" />;
- Use
className
instead ofclass
- Use
htmlFor
instead offor
Conditional Rendering
const isLoggedIn = true;
const message = <p>{isLoggedIn ? "Welcome back!" : "Please sign in."}</p>;
Inline Styles
const style = {
color: "blue",
fontSize: "20px"
};
const element = <p style={style}>Styled Text</p>;
JSX Must Return One Element
Wrap siblings in a parent:
return (
<div>
<h1>Title</h1>
<p>Paragraph</p>
</div>
);
Or use React Fragments:
return (
<>
<h1>Title</h1>
<p>Paragraph</p>
</>
);
Rendering Arrays
const items = ["One", "Two", "Three"];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
Self-Closing Tags
<input type="text" />
<br />
<img src="image.jpg" />
Comments in JSX
return (
<div>
{/* This is a comment */}
<p>Visible Text</p>
</div>
);