Introduction to React & JSX
React is a JavaScript library created by Meta for building user interfaces. Instead of manipulating the DOM directly, you describe what the UI should look like, and React figures out the most efficient way to update it.
1 Why React?
- Component-Based — Break UIs into small, reusable pieces. A Button, a Card, a Navbar — each is an independent component.
- Declarative — Describe the desired end state; React handles DOM updates automatically via the Virtual DOM.
- Unidirectional Data Flow — Data flows down from parent to child, making apps predictable and easy to debug.
- Huge Ecosystem — React Router, Redux, Zustand, React Query, Next.js, and thousands of community libraries.
2 Your First React App
The fastest way to start is create-react-app or Vite (recommended for speed):
Terminal — Create Vite + React project
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
3 JSX — JavaScript + HTML
JSX looks like HTML but it compiles down to React.createElement() calls. Key rules:
- Every component must return a single root element (use
<></>Fragment if needed). - Use
classNameinstead ofclass, andhtmlForinstead offor. - Embed JavaScript expressions inside
{ curly braces }. - Self-close tags that have no children:
<img />,<input />.
JSX — Basic Component
function Welcome({ name }) {
const greeting = "Hello";
return (
<div className="card">
<h1>{greeting}, {name}!</h1>
<p>Welcome to React. Today is {new Date().toDateString()}.</p>
<img src="/avatar.png" alt="User avatar" />
</div>
);
}
// Render it
export default function App() {
return <Welcome name="Balaji" />;
}
4 JSX Expressions & Ternaries
JSX — Expressions
const isLoggedIn = true;
const score = 87;
return (
<div>
{/* Ternary */}
{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
{/* Short-circuit */}
{score > 90 && <span className="badge">Top Scorer 🏆</span>}
{/* Expressions in attributes */}
<div className={isLoggedIn ? "dashboard" : "login-page"}>...</div>
</div>
);
5 Code Challenge
Challenge: Create a
ProfileCard component that accepts name, role, and avatar props and renders them in a styled card. Display a "⭐ Admin" badge only if a prop isAdmin is true.