Components & JSX
What React is
A JavaScript library for building user interfaces from components: reusable pieces like Navbar, ProductCard and Button. You describe what the UI should look like for the current data, and React updates the page efficiently when the data changes.
A component is a function that returns JSX
function Welcome() {
return <h1 className="title">Hello, React!</h1>;
}
JSX looks like HTML inside JavaScript, with some differences:
classNameinstead ofclass, andhtmlForinstead offor.- Every tag must close:
<img />,<br />. - One parent element, or a fragment
<>…</>. - JavaScript goes inside
{ }:<p>{user.name}</p>,<p>{2 + 2}</p>. - Inline styles are objects:
style={{ color: "red", fontSize: 18 }}. - Event handlers are camelCase:
onClick={handleClick}.
Composition
Build pages from small components:
function App() {
return (
<>
<Navbar />
<ProductList />
<Footer />
</>
);
}
Component names start with a capital letter.
Conditional rendering
{isLoggedIn ? <Dashboard /> : <Login />}
{items.length === 0 && <p>No items yet</p>}
💡 Start a project with npm create vite@latest, choosing React, or a framework like Next.js.
Example
// App.jsx
function Badge({ text }) {
return <span className="badge">{text}</span>;
}
function ProfileCard() {
const user = { name: "Ana", role: "Frontend developer", online: true };
return (
<div className="card">
<h2>{user.name}</h2>
<p>{user.role}</p>
{user.online ? <Badge text="Online" /> : <Badge text="Away" />}
</div>
);
}
export default function App() {
return (
<main style={{ fontFamily: "sans-serif", padding: 16 }}>
<h1>Team</h1>
<ProfileCard />
</main>
);
}
// 💻 Run in a Vite + React project